I take on the C # project, and when testing it, I get errors. The error is that the log file could not be written because it is being used by another process. Here is the code:
public void WriteToLog(string msg) { if (!_LogExists) { this.VerifyOrCreateLogFile(); // Creates log file if it does not already exist. } // do the actual writing on its own thread so execution control can immediately return to the calling routine. Thread t = new Thread(new ParameterizedThreadStart(WriteToLog)); t.Start((object)msg); } private void WriteToLog(object msg) { lock (_LogLock) { string message = msg as string; using (StreamWriter sw = File.AppendText(LogFile)) { sw.Write(message); sw.Close(); } } }
_LogLock is defined as a class variable:
private object _LogLock = 0;
Based on my research and the fact that this has been working in the production system for several years, I donβt know what the problem is. The lock should prevent another thread from trying to write to the log file.
The changes I made that need to be tested are a lot more than using logs. We basically add debug mode to save much more information in the log than we used to save.
Thanks for any help!
EDIT:
Thanks for the quick answers! VerifyOrCreateLogFile () uses _LogLock in the code, so this should not be a problem. He makes some entries in the log before it fails, so he does not have time to create a file.
It seems that the problem is that previously only one class created an instance of the log class, and now I have added instances to other classes. It makes sense that this will create problems. Changing the _LogLock field for static fixes the problem.
Thanks again!
source share