Tuesday, March 13, 2012

Thread safety issue

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!

Fengthe 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)

"Feng" <Feng@.discussions.microsoft.com> wrote in message
news:159CE973-735B-4ED4-BC21-EA7BA0760E20@.microsoft.com...
> 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

0 comments:

Post a Comment