多线程里面要写日志,有时候会遇到文件已被其它线程占用的问题,但是用lock也解决不了lock (sw)
{
CreateLogFile();
sw = new StreamWriter(GetFileName(), true);
sw.Write(expStr);
sw.Close();
}一样没办法解决
{
CreateLogFile();
sw = new StreamWriter(GetFileName(), true);
sw.Write(expStr);
sw.Close();
}一样没办法解决
解决方案 »
- 帮我看下“@list不是存储过程getdataset的参数”
- static是否会导致内存问题?
- 如何在水晶报表中取得一部分内容?
- 请问如何点击一个链接时,新窗口(有参数传递)不弹出,而是直接跳转
- 如何在Form没有打开之前,通过Timer定时5秒内判断按下Shift键没有?
- 菜鸟的高难度问题,在线等,分不够可以再加!
- 急!!c#里面如何打印word文件
- c#中有没有用于视频捕捉窗口建立的函数?
- WEB程序用WMI读取网卡地址的一点问题。请各位帮我看一下。
- comboBox可以根据设定的ValueMember来获取DisplayMember值吗?
- SqlDataAdapter.Update为何不能实现更新数据到数据库中去?
- 从字符串提取表名 [可加分]
你可以申明一个静态变量
static object obj= new object();
lock(obj)
{
......
}
{
private static Log log = new Log();
public static AddLong(Exception ex)
{
lock(Log.log)
{
Log.log.WriteLog(ex);
}
}
private WriteLog(Exception ex)
{
DateTime dateTime = DateTime.Now;
string messageString = ex.Message;
string sourceString = ex.Source;
string stacktrace = ex.StackTrace;
string expStr = "";
expStr += string.Format(" <exception>\r\n");
expStr += string.Format(" <Time>{0}</Time>\r\n", dateTime.ToString());
expStr += string.Format(" <Message>{0}</Message>\r\n", messageString);
expStr += string.Format(" <Source>{0}\r\n", sourceString);
expStr += string.Format(" </Source>\r\n");
expStr += string.Format(" <StackTrace>{0}\r\n", stacktrace);
expStr += string.Format(" </StackTrace>\r\n");
expStr += string.Format(" </exception>\r\n");
CreateLogFile();
StreamWriter sw = new StreamWriter(GetFileName(), true);
sw.Write(expStr);
sw.Close();
}
}