接上回:
仅作入门之用参考
多线程在执行的时候调试很麻烦,特别是在运行之后出错,这里我们就需要对线程进行日志处理
多线程运行时出错时有可能会引起整个线程池的崩溃,从而引起进程的意外关掉,那么在写程序的时候我们一方面要在可能出错的地方try{}catche{},另外一个好习惯就是写日志,发一个日之类
发一个日志函数
///
/// 写入日志 by crazycoder
/// http://www.crazycoder.cn/首发
///
///
日志文件名,不需要带路径
///
日志内容,单位为行
public static void WriteLog(string fileName,string content)
{
//获取日志文件物理路径
string path = Util.CrazyCoderGetMapPath(fileName);
try
{
if (!System.IO.File.Exists(path))
{
StreamWriter sw = System.IO.File.CreateText(path);
sw.WriteLine("---日志开始---" + DateTime.Now.ToString());
sw.Flush();
sw.Close();
}
StreamWriter sw2 = System.IO.File.AppendText(path);
//每个日志写一行 crazycoder.cn
sw2.WriteLine("--" + DateTime.Now.ToString() + "---" + content);
sw2.Flush();
sw2.Close();
}
catch
{
}
}
为了兼容web与Form应用程序,我们采用了一个GetMapPath方法,贴上代码
///
/// 获得当前绝对路径 by crazycoder.cn 含web和winform应用程序方法
///
///
指定的路径
///
public static string CrazyCoderGetMapPath(string strPath)
{
if (HttpContext.Current != null)
{
//如果是web
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
if (strPath.StartsWith("~/"))
strPath = strPath.Substring(2);
else if (strPath.StartsWith("/"))
strPath = strPath.Substring(1);
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
}
通过这两个方法,我们在线程开始和结束的地方写上日志
同时在容易出错的地方,在try catch的地方写日志,就很容易知道多线程出错的地方,并方便的进行调试
最新评论