本文介绍了asp.net mvc 4,线程被模型绑定改变了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC 4应用程序中使用了自定义ModelBinder,但在与global.asax中的请求事件处理程序不同的线程上调用了它,这使在ThreadLocal中设置性能分析上下文失败.

I am using a custom ModelBinder in an MVC 4 application, but it is invoked on a different thread than the request event handlers in global.asax, and this makes setting up a performance profiling context in a ThreadLocal fail.

threadId在每一行的开头放在括号中,您可以看到在调用模型绑定时该线程发生了变化,并且该线程是执行控制器操作(索引)的线程.

The threadId is in brackets at the start of each line, and you can see that the thread changes when the model binding is invoked, and that is the thread in which the controller action (Index) is executed.

[33] | ERROR | MyApp.MvcApplication | Application_BeginRequest
[33] | ERROR | MyApp.MvcApplication | Application_AuthenticateRequest
[33] | ERROR | MyApp.MvcApplication | Application_AuthorizeRequest
[33] | ERROR | MyApp.MvcApplication | Application_ResolveRequestCache
[33] | ERROR | MyApp.MvcApplication | Application_AcquireRequestState
[33] | ERROR | MyApp.MvcApplication | Application_PreRequestHandlerExecute
[52] | ERROR | Binders.MyModelBinder | ModelBinder
[52] | ERROR | MyApp.Controllers.MyController | Index

知道为什么会这样吗?我的期望是,控制器方法将始终在与global.asax

Any idea why this is happening? My expectation was that the controller methods would always be invoked on the same thread as the application event handlers in global.asax

推荐答案

事实证明,我的核心假设不正确-控制器操作未与事件处理程序在同一线程上调用.

Turns out that my core assumption was incorrect - the controller actions are not invoked on the same thread as the event handlers.

这是Environment.StackTrace的片段,显示了异步进程(在另一个线程上)正在调用的控制器动作.

Here is a snippet from Environment.StackTrace that shows the controller action being invoked by an asynchronous process (on another thread).

at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

好像我将性能分析上下文存储在会话中.

Looks like I'll be storing my performance profiling context in the session instead.

这篇关于asp.net mvc 4,线程被模型绑定改变了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:22
查看更多