tags:

views:

28

answers:

3

hello All, I have a question regarding the synchronization in multi threading.

I have a function called send which i am calling in a for loop for every data row.

This function creates threads to send emails to different people.

Public Sub send(ByVal Conn As Data.DataRow, ByVal job As Data.DataRow) MyThread = New Thread(AddressOf Me.start) MyThread.Start() End Sub

But every thread created is writing to a log file at different points of time. So, there are very high chances that 2 threads write to the same file at the same time. So, do i need to use any kind of synchronization mechanisms here ? or is it fine without them ? If yes, can any one please tell me what to use and where to use.

+1  A: 

To prevent multiple threads from writing at the same time, use SyncLock. For example, myLogFile is your log file:

SyncLock myLogFile
    myLogFile.WriteLine("message");
End SyncLock
Jim Mischel
A: 

You will have an access error if one thread is blocking the file because it is writing to it. You can handle the exception, have the current thread wait and then write to the file.

boolean AttemptingToWrite = true

while (AttemptingToWrite)
try
   WriteToLog()
   AttemptinToWrite = false
catch(ex as exception
  system.threading.thread.sleep(100)
end try
end while
Achilles
Haha, it's like VB.NET and C# had a baby ;)
Dan Tao
+1  A: 

Several approaches:

Your thread can obtain a lock on your logger object prior to calling the loggers log methods. This makes it the callers responsibility to lock.

Optionally you can move the locking responsibility into the logger object by having it manage the locking. See Jim's answer.

If you aren't wrapping your logging functionality into a separate object then simply create an object in your code that you can lock on.

Additionally, I wouldn't spawn a thread per record unless you know you will always have a small number of records. Otherwise you'll create context switch thrashing and hurt perf. Look into the Thread.QueueUserWorkItem() static method.

JasonCoder