ASP.NET mvc4 Controllder 同步还是异步

从抽象类Controller 的定义可以看出他 同时实现了 IAsyncController, IController

   public abstract class Controller : ControllerBase, IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IController, IAsyncManagerContainer
    {
        protected Controller();
    }

IAsyncController 就表示异步。

通过属性 DisableAsyncSupport 属性来判断是同步还是异步执行  DisableAsyncSupport=true 表示同步 DisableAsyncSupport=false 表示异步。

但是即使执行BeginExecute/EndExecute 方法,Controller也不一定是 异步方式执行,如下代码片段。

public class HomeController : Controller
    {
        protected override bool DisableAsyncSupport
        {
            get { return false; }
        }

        public new HttpResponse Response
        {
            get { return System.Web.HttpContext.Current.Response; }
        }

        /// <summary>
        /// 同步执行
        /// </summary>
        /// <param name="requestContext"></param>
        protected override void Execute(RequestContext requestContext)
        {
            Response.Write("Execute(); <br/>");
            base.Execute(requestContext);
        }

        /// <summary>
        /// 同步执行
        /// </summary>
        protected override void ExecuteCore()
        {
            Response.Write("ExecuteCore(); <br/>");
            base.ExecuteCore();
        }

        /// <summary>
        /// 同步异步都会执行
        /// </summary> 
        protected override IAsyncResult BeginExecute(RequestContext requestContext,
            AsyncCallback callback, object state)
        {
            Response.Write("BeginExecute(); <br/>");
            return base.BeginExecute(requestContext, callback, state);
        }

        /// <summary>
        /// 同步异步都会执行
        /// </summary>
        /// <param name="asyncResult"></param>
        protected override void EndExecute(IAsyncResult asyncResult)
        {
            Response.Write("EndExecute(); <br/>");
            base.EndExecute(asyncResult);
        }

        /// <summary>
        /// 异步执行
        /// </summary>  
        protected override IAsyncResult BeginExecuteCore(AsyncCallback callback,
            object state)
        {
            Response.Write("BeginExecuteCore(); <br/>");
            return base.BeginExecuteCore(callback, state);
        }

        /// <summary>
        /// 异步执行
        /// </summary>
        /// <param name="asyncResult"></param>
        protected override void EndExecuteCore(IAsyncResult asyncResult)
        {
            Response.Write("EndExecuteCore(); <br/>");
            base.EndExecuteCore(asyncResult);
        }

        public ActionResult Index()
        {
            return Content("Index();<br/>");
        }
    }

Controller 还继承了一个IAsyncController 接口,这个异步接口并不是指 Controller 是否异步, 而是 Action 方法是否异步执行,在MVC4以前 Action 的异步是通过

定义XxxAsync/XxxCompleted 形式定义异步Action,新版本中为了兼容旧版 所以引用了IAsyncController 

在4.0后 Action 通过返回Task的方式来定义是否异步执行Action。

原文地址:https://www.cnblogs.com/dragon-L/p/5244114.html