我正在接管一个C#项目,在测试时我遇到了错误.错误是无法写入日志文件,因为它正被另一个进程使用.这是代码:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
_LogLock定义为类变量:
private object _LogLock = 0;
Run Code Online (Sandbox Code Playgroud)
根据我的研究以及现在几年来在生产系统中运行良好的事实,我不知道问题可能是什么.锁应该阻止另一个线程尝试写入日志文件. …