前段时间在做项目时,系统是个多线程程序,几个线程都需要写日志,主线程和通讯线程经常在写日志时打架,为了解决这个问题,考虑在写日志的方法中加锁。代码如下:
/// <summary>
/// 写日志时加锁
/// </summary>
private static object m_Lock = new object();
/// <summary>
/// 写日志文件的接口函数,此函数只向指定的文件写入字符串
/// </summary>
/// <param name="DestFileName"></param>
/// <param name="fmt"></param>
/// <returns></returns>
public static int TP_WriteAppLogFileEx(string DestFileName, string fmt)
{
string strLogFile = System.Environment.CurrentDirectory+"\\Log\\"+DateTime.Now.ToString("yyyyMMdd")+".log";
if (strLogFile != DestFileName)
{
DestFileName = strLogFile;
}
int iWriteAppLogFile = 0;
lock (m_Lock)
{
iWriteAppLogFile=TP_WriteAppLogFile(DestFileName, fmt);
}
return iWriteAppLogFile;
}
public static int TP_WriteAppLogFile(string DestFileName, string fmt)
{
try
{
FileInfo file = new FileInfo(DestFileName);
if (!file.Exists)
{
file.Create();
}
//定位到文件尾
StreamWriter stream = file.AppendText();
//写当前的时间
stream.Write(DateTime.Now.ToString("HH:mm:ss fff "));
//写用户传过来的字符串
stream.WriteLine(fmt);
//最后记着要关了它
stream.Close();
}
catch (Exception e)
{
}
return 0;
}
经过加锁处理后,多线程写日志打架的问题得到了解决。