在Global的Application_Error一般处理没有被捕获的异常,写入日志,并返回用户信息。
在访问量很小的情况下,可以用下面的代码:
<span style="font-size:14px;">lock (obj)
{
using (FileStream fs = new FileStream(LogPath, FileMode.Append, FileAccess.Write))
{
string info = System.Environment.NewLine + System.Environment.NewLine + Server.GetLastError().ToString();//获取异常信息
byte[] data = Encoding.Default.GetBytes(info);
fs.Write(data, 0, data.Length);
}
}</span>
上面lock的是在Global中定义的一个静态变量,锁一个静态变量,单例,阻止了IIS应用程序池可能有n个不同的对象在执行这个方法产生的争抢。
在访问量很大的情况下,上面的代码可能会让用户等待很长的响应时间,这时就可以用到ThreadPool.QueueUserWorkItem
<span style="font-size:14px;">Common文件夹下新建一个类,LogHelper
public class LogHelper
{
public static Queue<string> ExceptionInfo = new Queue<string>();
public static string LogRootPath;//存放日志文件夹路径
static LogHelper()
{
ThreadPool.QueueUserWorkItem(o =>
{
while(true)
{
if(ExceptionInfo.Count > 0)
{
string info = ExceptionInfo.Dequeue();
string FilePath =Path.Combine(LogRootPath, DateTime.Now.ToString("yyy-MM-dd") + ".txt");
using (FileStream fs = new FileStream(FilePath, FileMode.Append, FileAccess.Write))
{
info = System.Environment.NewLine + System.Environment.NewLine+ info;//获取异常信息
byte[] data = Encoding.Default.GetBytes(info);
fs.Write(data, 0, data.Length);
}
}
}
});
}
}
在Application_Error函数中:
if (string.IsNullOrEmpty(Common.LogHelper.LogRootPath))//设置日志目录路径
Common.LogHelper.LogRootPath = Request.MapPath(@"/ErrorLog");
Common.LogHelper.ExceptionInfo.Enqueue(Server.GetLastError().ToString());
//加入队列之后立即就可以返回
Response.Redirect(@"/Error.aspx");</span>
其实这里也并不一定需要ThreadPool.QueueUserWorkItem这个方法,仅需要执行一个写日志的函数,开个子线程也是可以的。
ThreadPool.QueueUserWorkItem主要作用是将方法排入队列以便执行。在线程池中寻找可用线程来执行这个方法,在一定程度上是能合理分配资源。
但是由于ThreadPool.QueueUserWorkItem是依次执行,可能会导致某些任务在很长时间后才会被执行到,甚至一个函数被阻塞,后面的函数都不会被执行,或者重启IIS导致很多任务还没有被执行就被丢弃。