I have created a Logging utility class for my multithreaded C# app. In order to ensure safe access to the file by all threads, I am locking on a static object as follows:
private static readonly object locker = new object();
public static void WriteLog(String message, params Object[] args)
{
try
{
string filename = m_baseDir + GetFilenameYYYMMDD("_LOG", ".log");
lock (locker)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true);
String msg = String.Format(message, args);
sw.WriteLine(System.DateTime.Now.ToString() + " -" + msg);
sw.Close();
}
}
catch (Exception ex) { Console.WriteLine(ex); }
}
However, when my application runs, I am still getting a System.IO.Exception
on the line that initialises the sw
variable.
System.IO.IOException: The process cannot access the file 'C:\\MyApp\\bin\\Debug\\Logs\\MyApp_2017_09_18_LOG.log' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
I do get messages in the Log though, so some thread(s) must be able to write to the file.
How can I fix this so all threads can access the file?
I got the same problem like before:
I just use this:
sw.Flush();
sw.Close();
After the execution has done.
You can try this sw.Dispose();
also.
Hope it helps:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.