为ASP.NET MVC扩展异步Action功能
回的 IAsyncResult,以及另一个对于EndXxx方法的引用。在AsyncActionResult的ExecuteResult方法中将会保 存这两个对象,以便在AsyncMvcHandler的EndProcessRequest方法中重新获取并使用。根据“惯例”,我 们还需要定义一个扩展方法,方便开发人员在Action方法中返回一个AsyncActionResult。具体实现非常 容易,在这里就展示一下异步Action的编写方式:
[AsyncAction] public ActionResult AsyncAction(AsyncCallback asyncCallback, object asyncState) { SqlConnection conn = new SqlConnection("...;Asynchronous Processing=true"); SqlCommand cmd = new SqlCommand("WAITFOR DELAY ''00:00:03'';", conn); conn.Open(); return this.Async( cmd.BeginExecuteNonQuery(asyncCallback, asyncState), (ar) => { int value = cmd.EndExecuteNonQuery(ar); conn.Close(); return this.View(); }); } 至此,似乎AsyncMvcHandler也无甚秘密可言了: public class AsyncMvcHandler : IHttpAsyncHandler, IRequiresSessionState { public AsyncMvcHandler( Controller controller, IControllerFactory controllerFactory, RequestContext requestContext) { this.Controller = controller; this.ControllerFactory = controllerFactory; this.RequestContext = requestContext; } public Controller Controller { get; private set; } public RequestContext RequestContext { get; private set; } public IControllerFactory ControllerFactory { get; private set; } public HttpContext Context { get; private set; } public IAsyncResult BeginProcessRequest( HttpContext context, AsyncCallback cb, object extraData) { this.Context = context; this.Controller.SetAsyncCallback(cb).SetAsyncState(extraData); try { (this.Controller as IController).Execute(this.RequestContext); return this.Controller.GetAsyncResult(); } catch { this.ControllerFactory.ReleaseController(this.Controller); throw; } } public void EndProcessRequest(IAsyncResult result) { try { HttpContext.Current = this.Context; ActionResult actionResult = this.Controller.GetAsyncEndDelegate()(result); if (actionResult != null) { actionResult.ExecuteResult(this.Controller.ControllerContext); } } finally { this.ControllerFactory.ReleaseController(this.Controller); } } } 在BeginProcessRequest方法中将保存当前Context——这点很重要,HttpContext.Current是基于 CallContext的,一旦经过一次异步回调HttpContext.Current就变成了null,我们必须重设。接着将接收 到的AsyncCallback和AsyncState保留,并使用框架中现成的Execute方法执行控制器。当Execute方法返 回时一整个Action方法的调用流程已经结束,这意味着其调用结果——即IAsyncResult和EndDelegate对 象已经保留。于是将IAsyncResult对象取出并返回。至于EndProcessRequest方法,只是将 BeginPro |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |