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

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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!
Why?
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
TestGuiLog("StreamWriterP.txt")).Write("StreamWriterDemoP")
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)
sw.Close()

SC.WriteLine("End metod with " + pstr + " Ok:)")
Else
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.Close()
m_swf = Nothing
End If

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

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

End Class
 
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!
Why?
It's Bug?
Or it's high way of thinking?
May be needs any qualifier before class-fields?
Help me please:)

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

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.
 
Back
Top