我想log Thread-ID
是为了跟踪请求并使日志文件可读。
所以,我最初的尝试是logging in Global.asax
,就像这样:
protected void Application_BeginRequest()
{
log4net.ILog writer = log4net.LogManager.GetLogger(this.GetType());
writer.InfoFormat("Gotta service a request. Id = {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
}
protected void Application_EndRequest()
{
log4net.ILog writer = log4net.LogManager.GetLogger(this.GetType());
writer.InfoFormat("Completed servicing a request. Id = {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
}
但是当我看到日志文件时,这很奇怪。
2014-06-16 20:27:06,018 - Gotta service a request. Id = 286 --> From Application_BeginRequest()
2014-06-16 20:27:06,042 - Servicing Request Thread-Id = 286 --> this message comes from controller
2014-06-16 20:27:06,043 - Thread-Id = 286 --> this message comes from controller
2014-06-16 20:27:06,237 - Completed servicing a request. Id = 287 --> From Application_EndRequest()
在Application_Start
中,Thread-Id
为286
,但当它返回Application_EndRequest
时,Thread-Id changed to 287
。
是不是一个服务于整个HTTP request
的线程?
任何想法为什么?
答案 0 :(得分:2)
请求是单线程处理的,但这并不意味着它在整个请求中都是相同的线程。
请求可以“跳转”线程,您仍然可以保证按顺序执行,但不能保证在整个运行的同一个线程上运行。