服务ASP.NET Web-API HTTP请求涉及多少个线程?

时间:2014-06-16 15:09:03

标签: c# asp.net .net asp.net-mvc asp.net-web-api

我想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-Id286,但当它返回Application_EndRequest时,Thread-Id changed to 287

是不是一个服务于整个HTTP request的线程?

任何想法为什么?

1 个答案:

答案 0 :(得分:2)

请求是单线程处理的,但这并不意味着它在整个请求中都是相同的线程。

请求可以“跳转”线程,您仍然可以保证按顺序执行,但不能保证在整个运行的同一个线程上运行。