It's Bug? Or it's high way of thinking?

It's Bug? Or it's high way of thinking?

Post by VG1wU3E6K » Tue, 07 Sep 2004 21:45:03

I'm write string in textfile in this sample. When it done, i mast have three
files. Every file mast contain one string. Realy only one file contain
string, what maked inside of my metod (Write). vbc-compiler don't say about
erros. When i define variable as class-field, StreamWriter to act very
strange. It didn't write string in file!
It's Bug?
Or it's high way of thinking?
May be needs any qualifier before class-fields?
Help me please:)

Imports System.IO
Imports System.Text
Imports SC = System.Console

Module Simple
Sub Main()
Dim rez As Object = (New
End Sub
End Module

Public Class TestGuiLog

Friend m_swp As StreamWriter
Friend m_swf As StreamWriter

Sub New()
End Sub

Sub New(ByRef pstr As String)
m_swf = New StreamWriter("StreamWriterF.txt", True)
m_swf.WriteLine("StreamWriterDemoFC on {0}", DateTime.Now)

m_swp = New StreamWriter(pstr, True)
SC.WriteLine("This is constructor with " + pstr )
End Sub

Function Write(ByVal pstr As String) As Integer
If Not (m_swp Is Nothing) Then
SC.WriteLine("Begining metod with " + pstr )
m_swp.WriteLine( pstr + " on {0}", DateTime.Now)
m_swf.WriteLine("StreamWriterDemoFM on {0}", DateTime.Now)

Dim sw As New StreamWriter("StreamWriter.txt", True)
sw.WriteLine("StreamWriterDemo on {0}", DateTime.Now)

SC.WriteLine("End metod with " + pstr + " Ok:)")
SC.WriteLine("End metod with " + pstr + " bad:(")
Return 0
End If
Return 1
End Function

Protected Overrides Sub Finalize()
If Not (m_swf Is Nothing) Then
m_swf = Nothing
End If

If Not (m_swp Is Nothing) Then
m_swp = Nothing
End If

SC.WriteLine("This is dectructor:)")
End Sub

End Class

It's Bug? Or it's high way of thinking?

Post by Jon Skeet » Wed, 08 Sep 2004 19:10:23

<"=?Utf-8?B?VG1wU3E6KQ==?=" <TmpSq:)>>

I believe the problem is that you're closing the StreamWriter in your
finalizer. By that stage, the StreamWriters themselves may have been

If you flush the StreamWriters every time you write, that *might* sort
things out (and probably will, in fact) but relying on finalizers for
this kind of thing is a bad idea. You should be explicitly closing the
streamwriters when you're done with them, not when the garbage
collector decides to kick in.

Jon Skeet - < XXXX@XXXXX.COM > ~skeet
If replying to the group, please do not mail me too