Thread safe TextWriter question

  • Thread starter Thread starter fniles
  • Start date Start date
F

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()
 
fniles said:
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
 
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()
 
fniles said:
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
 
Back
Top