G
Guest
My application uses a singleton static class for writing entries to a log
file. The location and name of the log-file is read from web.config each time
an entry is written, but has the current date inserted into its name. For
example, the string:
c:\inetpub\wwwroot\myapp\log.txt
will be changed to:
c:\inetpub\wwwroot\myapp\log_20060216.txt
However, as we have many concurrent users on the site at once, each
generating hundreds of log file entries a minute, we're finding that multiple
threads are calling the same code at the same time and we're getting filename
with multiple date stamps. Ie:
c:\inetpub\wwwroot\myapp\log_20060216_20060216.txt
I'm sure this is to do with the following code not being thread-safe despite
the "lock" critical section statement:
string sLog_File_Path = ConfigurationManager.AppSettings["logfilepath"];
lock (FoLockObject) {
sLog_File_Path = Path.Combine(Path.GetDirectoryName(sLog_File_Path),
Path.GetFileNameWithoutExtension(sLog_File_Path) + "_" +
DateTime.Now.ToString("yyyyMMdd") +
Path.GetExtension(sLog_File_Path));
}
Can anyone offer advice on the correct way to protect code that is
vulnerable to threading issues. I'm aware of synchronization objects such as
Mutex's but am unsure how to use them with static classes. A stright forward
example in C# without being too clever would be very handy
Thanks
Ben
file. The location and name of the log-file is read from web.config each time
an entry is written, but has the current date inserted into its name. For
example, the string:
c:\inetpub\wwwroot\myapp\log.txt
will be changed to:
c:\inetpub\wwwroot\myapp\log_20060216.txt
However, as we have many concurrent users on the site at once, each
generating hundreds of log file entries a minute, we're finding that multiple
threads are calling the same code at the same time and we're getting filename
with multiple date stamps. Ie:
c:\inetpub\wwwroot\myapp\log_20060216_20060216.txt
I'm sure this is to do with the following code not being thread-safe despite
the "lock" critical section statement:
string sLog_File_Path = ConfigurationManager.AppSettings["logfilepath"];
lock (FoLockObject) {
sLog_File_Path = Path.Combine(Path.GetDirectoryName(sLog_File_Path),
Path.GetFileNameWithoutExtension(sLog_File_Path) + "_" +
DateTime.Now.ToString("yyyyMMdd") +
Path.GetExtension(sLog_File_Path));
}
Can anyone offer advice on the correct way to protect code that is
vulnerable to threading issues. I'm aware of synchronization objects such as
Mutex's but am unsure how to use them with static classes. A stright forward
example in C# without being too clever would be very handy
Thanks
Ben