Thread safety issue

G

Guest

In my VB.Net ASP project, I have a function in a module (same thing as a
static function in C#'s terms) that is shared by all the sessions. What is
does once called is to write messages into a common log file that's also
shared by all the sessions. To make sure it is thread safe, I use the Monitor
class to sync it up. Here is the simplified version of that function"

Public Sub WriteLog(ByVal strMsg As String)
Dim oWriter As StreamWriter
Dim strLogPath As String = "C:\Logs\test.log"

If Not File.Exists(strLogPath) Then
oWriter = File.CreateText(strLogPath)
Else
oWriter = File.AppendText(strLogPath)
End If

Monitor.Enter(oWriter)
Try
oWriter.WriteLine(strMsg)
oWriter.Flush()
oWriter.Close()
Finally
Monitor.Exit(oWriter)
End Try
End Sub

My problem is that this code doesn't seem to do what I want it to do. I am
still getting error that says "The process cannot access the file
'C:\Logs\test.log' because it is used by another process.". Why is this
happening? I must be doing something wrong. Can some one tell me how I should
do this?

Thanks a million!

Feng
 
B

Bruce Barker

the object you are locking on is local to the call, so threads do not block
each other because they are all locking different objects.

you need to lock on a static object. you could use the class type, but there
is a performance hit for this, better to create an actual object to lock on.
also the File.Exists need to be in lock.

-- bruce (sqlwork.com)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top