Home All Groups Group Topic Archive Search About

Thread safe TextWriter question

Author
31 Jul 2006 7:00 PM
fniles
Is this the correct syntax to make a Textwriter thread safe ? Thank you.

Dim swError As TextWriter
Dim swErrorSync As TextWriter
swError = New StreamWriter(Application.StartupPath & "\Log.txt", True)
swErrorSync = swError.Synchronized(swError)
swError.Write(Now & vbCrLf)
swError.Close()

Author
31 Jul 2006 7:16 PM
David Browne
"fniles" <fni***@pfmail.com> wrote in message
news:OuPMeONtGHA.4748@TK2MSFTNGP03.phx.gbl...
> Is this the correct syntax to make a Textwriter thread safe ? Thank you.
>
> Dim swError As TextWriter
> Dim swErrorSync As TextWriter
> swError = New StreamWriter(Application.StartupPath & "\Log.txt", True)
> swErrorSync = swError.Synchronized(swError)
> swError.Write(Now & vbCrLf)
> swError.Close()
>

No.  Not quite.  Threads should write to swErrorSync.  And it's not clear
what code different threads are running.  This snippet, as a whole, is
definitely not thread-safe.

David
Author
31 Jul 2006 8:16 PM
fniles
I am sorry, I typed in incorrectly.
Pls tell me if the following is correct and thread safe.
Thanks.

Dim swError As TextWriter
Dim swErrorSync As TextWriter

swError = New StreamWriter(Application.StartupPath & "\Log.txt", True)
swErrorSync = swError.Synchronized(swError)
swErrorSync .Write(Now & vbCrLf)
swError.Close()
swErrorSync.Close()

Show quoteHide quote
"David Browne" <davidbaxterbrowne no potted m***@hotmail.com> wrote in
message news:u%232MdXNtGHA.2020@TK2MSFTNGP03.phx.gbl...
>
> "fniles" <fni***@pfmail.com> wrote in message
> news:OuPMeONtGHA.4748@TK2MSFTNGP03.phx.gbl...
>> Is this the correct syntax to make a Textwriter thread safe ? Thank you.
>>
>> Dim swError As TextWriter
>> Dim swErrorSync As TextWriter
>> swError = New StreamWriter(Application.StartupPath & "\Log.txt", True)
>> swErrorSync = swError.Synchronized(swError)
>> swError.Write(Now & vbCrLf)
>> swError.Close()
>>
>
> No.  Not quite.  Threads should write to swErrorSync.  And it's not clear
> what code different threads are running.  This snippet, as a whole, is
> definitely not thread-safe.
>
> David
>
Author
31 Jul 2006 8:38 PM
David Browne
Show quote Hide quote
"fniles" <fni***@pfmail.com> wrote in message
news:uyKbF5NtGHA.644@TK2MSFTNGP03.phx.gbl...
>I am sorry, I typed in incorrectly.
> Pls tell me if the following is correct and thread safe.
> Thanks.
>
> Dim swError As TextWriter
> Dim swErrorSync As TextWriter
>
> swError = New StreamWriter(Application.StartupPath & "\Log.txt", True)
> swErrorSync = swError.Synchronized(swError)
> swErrorSync .Write(Now & vbCrLf)
> swError.Close()
> swErrorSync.Close()



No.  That code is not thread-safe.  If multiple threads execute that code
you will not necessarilly get correct, whole, ordered log entries.

If you refactored the code so that a single thread opened and closed the
file, while multiple threads accessed the syncronized StreamWriter wrapper,
then it would be.

David