溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么

發(fā)布時(shí)間:2021-10-29 16:22:37 來源:億速云 閱讀:114 作者:柒染 欄目:編程語言

ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

Action方法的執(zhí)行具有兩種基本的形式,即同步執(zhí)行和異步執(zhí)行,而在ASP.NETMVC的整個(gè)體系中涉及到很多同步/異步的執(zhí)行方式,雖然在前面相應(yīng)的文章中已經(jīng)對(duì)此作了相應(yīng)的介紹,為了讓讀者對(duì)此有一個(gè)整體的了解,我們來做一個(gè)總結(jié)性的論述。

一、MvcHandler的同步與異步

對(duì)于ASP.NET MVC應(yīng)用來說,MvcHandler是最終用于處理請(qǐng)求的HttpHandler,它是通過UrlRoutingModule這個(gè)實(shí)現(xiàn)了URL路由的HttpModule被動(dòng)態(tài)映射到相應(yīng)的請(qǐng)求的。MvcHandler借助于ControllerFactory激活并執(zhí)行目標(biāo)Controller,并在執(zhí)行結(jié)束后負(fù)責(zé)對(duì)激活的Controller進(jìn)行釋放,相關(guān)的內(nèi)容請(qǐng)參與本書的第3章“Controller的激活”。如下面的代碼片斷所示,MvcHandler同時(shí)實(shí)現(xiàn)了IHttpHandler和IHttpAsyncHandler接口,所以它總是調(diào)用BeginProcessRequest/EndProcessRequest方法以異步的方式來處理請(qǐng)求。

public class MvcHandler : IHttpAsyncHandler, IHttpHandler, ...  {      //其他成員         IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData);      void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result);      void IHttpHandler.ProcessRequest(HttpContext httpContext);  }

二、Controller的同步與異步

Controller也具有同步與異步兩個(gè)版本,它們分別實(shí)現(xiàn)了具有如下定義的兩個(gè)接口IController和IAsyncController。當(dāng)激活的Controller對(duì)象在MvcHandler的BeginProcessRequest方法中是按照這樣的方式執(zhí)行的:如果Controller的類型實(shí)現(xiàn)了IAsyncController接口,則調(diào)用BeginExecute/EndExecute方法以異步的方式執(zhí)行Controller;否則Controller的執(zhí)行通過調(diào)用Execute方法以同步方式執(zhí)行。

public interface IController  {          void Execute(RequestContext requestContext);  }  public interface IAsyncController : IController  {          IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state);      void EndExecute(IAsyncResult asyncResult);  }

默認(rèn)情況下通過Visual Studio的向?qū)?chuàng)建的Controller類型是抽象類型Controller的子類。如下面的代碼片斷所示,Controller同時(shí)實(shí)現(xiàn)了IController和IAsyncController這兩個(gè)接口,所以當(dāng)MvcHandler進(jìn)行請(qǐng)求處理時(shí)總是以異步的方式來執(zhí)行Controller。

public abstract class Controller : ControllerBase, IController, IAsyncController, ...  {      //其他成員      protected virtual bool DisableAsyncSupport      {          get{return false;}      }  }

但是Controller類型具有一個(gè)受保護(hù)的只讀屬性DisableAsyncSupport用于表示是否禁用對(duì)異步執(zhí)行的支持。在默認(rèn)情況下,該屬性值為False,所以默認(rèn)情況下是支持Controller的異步執(zhí)行的。如果我們通過重寫該屬性將值設(shè)置為True,那么Controller將只能以同步的方式執(zhí)行。具體的實(shí)現(xiàn)邏輯體現(xiàn)在如下的代碼片斷中:BeginExecute方法在DisableAsyncSupport屬性為True的情況下通過調(diào)用Execute方法(該方法會(huì)調(diào)用一個(gè)受保護(hù)的虛方法ExecuteCore最終對(duì)Controller進(jìn)行同步執(zhí)行);否則通過調(diào)用BeginExecuteCore/EndExecuteCore以異步方式執(zhí)行Controller。

 public abstract class Controller: ...   {       //其他成員       protected virtual IAsyncResult BeginExecute(RequestContext requestContext,        AsyncCallback callback, object state)       {           if (this.DisableAsyncSupport)           {               //通過調(diào)用Execute方法同步執(zhí)行Controller          }          else         {              //通過調(diào)用BeginExecuteCore/EndExecuteCore方法異步執(zhí)行Controller          }  }      protected override void ExecuteCore();      protected virtual IAsyncResult BeginExecuteCore(AsyncCallback callback, object state);      protected virtual void EndExecuteCore(IAsyncResult asyncResult);  }

三、 ActionInvoker的同步與異步

包括Model綁定與驗(yàn)證的整個(gè)Action的執(zhí)行通過一個(gè)名為ActionInvoker的組件來完成,而它同樣具有同步和異步兩個(gè)版本,分別實(shí)現(xiàn)了接口IActionInvoker和IAsyncActionInvoker。如下面的代碼片斷所示,這兩個(gè)接口分別通過InvokeAction和BeginInvokeAction/EndInvokeAction方法以同步和異步的方式執(zhí)行Action。抽象類Controller中具有一個(gè)ActionInvoker屬性用于設(shè)置和返回用于執(zhí)行自身Action的ActionInvoker對(duì)象,而該對(duì)象最終是通過受保護(hù)需方法CreateActionInvoker創(chuàng)建的。

 public interface IActionInvoker   {       bool InvokeAction(ControllerContext controllerContext, string actionName);   }       public interface IAsyncActionInvoker : IActionInvoker   {       IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state);       bool EndInvokeAction(IAsyncResult asyncResult);  }     public abstract class Controller  {         //其它成員      public IActionInvoker ActionInvoker { get; set; }      protected virtual IActionInvoker CreateActionInvoker()  }

ASP.NET MVC真正用于Action方法同步和異步執(zhí)行的ActionInvoker分別是ControllerActionInvoker和AsyncControllerActionInvoker。如下面的代碼片斷所示,ControllerActionInvoker定義了一個(gè)受保護(hù)的方法GetControllerDescriptor用于根據(jù)指定的Controller上下文獲取相應(yīng)的ControllerDescriptor,它的子類AsyncControllerActionInvoker對(duì)這個(gè)方法進(jìn)行了重寫。

public class ControllerActionInvoker : IActionInvoker  {      //其它成員      protected virtual ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext);  }     public class AsyncControllerActionInvoker : ControllerActionInvoker,IAsyncActionInvoker, IActionInvoker  {      //其它成員    protected override ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext);

我們所有要了解的是在默認(rèn)情況下(沒有對(duì)Controller類型的ActionInvoker屬性進(jìn)行顯式設(shè)置)采用的ActionInvoker類型是哪個(gè)。ASP.NET MVC對(duì)Conroller采用的ActionInvoker類型的選擇機(jī)制是這樣的:

通過當(dāng)前的DependencyResolver以IAsyncActionInvoker接口去獲取注冊(cè)的ActionInvoker,如果返回對(duì)象不為Null,則將其作為默認(rèn)的ActionInvoker。

通過當(dāng)前的DependencyResolver以IActionInvoker接口去獲取注冊(cè)的ActionInvoker,如果返回對(duì)象不為Null,則將其作為默認(rèn)的ActionInvoker。

創(chuàng)建AsyncControllerActionInvoker對(duì)象作為默認(rèn)的ActionInvoker。

在默認(rèn)的情況下,當(dāng)前的DependencyResolver直接通過對(duì)指定的類型進(jìn)行反射來提供對(duì)應(yīng)的實(shí)例對(duì)象,所以對(duì)于前面兩個(gè)步驟返回的對(duì)象均為Null,所以默認(rèn)創(chuàng)建出來的ActionInvoker類型為AsyncControllerActionInvoker。我們可以通過如下一個(gè)簡(jiǎn)單的實(shí)例來驗(yàn)證這一點(diǎn)。在通過Visual Studio的ASP.NET MVC項(xiàng)目模板創(chuàng)建的空Web應(yīng)用中,我們創(chuàng)建了如下一個(gè)默認(rèn)的HomeController,在Action方法Index中直接通過ContentResult將ActionInvoker屬性的類型名稱呈現(xiàn)出來。

 public class HomeController : Controller   {         public ActionResult Index()       {           return Content("默認(rèn)ActionInvoker類型:" + this.ActionInvoker.GetType().FullName);       }  }

當(dāng)運(yùn)行該Web應(yīng)用時(shí),會(huì)在瀏覽器上產(chǎn)生如下的輸出結(jié)果,我們可以清楚地看到默認(rèn)采用的ActionInvoker類型正是AsyncControllerActionInvoker。

默認(rèn)ActionInvoker類型:System.Web.Mvc.Async.AsyncControllerActionInvoker

為了進(jìn)一步驗(yàn)證基于DependencyResolver對(duì)ActionInvoker的提供機(jī)制,我們將《ASP.NET MVC Controller激活系統(tǒng)詳解:IoC的應(yīng)用》創(chuàng)建的基于Ninject的自定義NinjectDependencyResolver應(yīng)用在這里。如下面的代碼片斷所示,在初始化NinjectDependencyResolver的時(shí)候,我們將IActionInvoker和IAsyncActionInvoker影射到兩個(gè)自定義ActionInvoker類型,即FooActionInvoker和FooAsyncActionInvoker,它們分別繼承自ControllerActionInvoker和AsyncControllerActionInvoker。

 public class NinjectDependencyResolver : IDependencyResolver   {       public IKernel Kernel { get; private set; }       public NinjectDependencyResolver()       {           this.Kernel = new StandardKernel();           AddBindings();       }       private void AddBindings()      {          this.Kernel.Bind<IActionInvoker>().To<FooActionInvoker>();          this.Kernel.Bind<IAsyncActionInvoker>().To<FooAsyncActionInvoker>();      }      public object GetService(Type serviceType)      {          return this.Kernel.TryGet(serviceType);      }      public IEnumerable<object> GetServices(Type serviceType)      {          return this.Kernel.GetAll(serviceType);      }  }  public class FooActionInvoker : ControllerActionInvoker  {}  public class FooAsyncActionInvoker : AsyncControllerActionInvoker  {}

在Global.asax中對(duì)NinjectDependencyResolver進(jìn)行注冊(cè)后運(yùn)行我們的程序,會(huì)在瀏覽器中得到如下的輸出結(jié)果。IAsyncActionInvoker和FooAsyncActionInvoker進(jìn)行了影射,NinjectDependencyResolver可以通過IAsyncActionInvoker提供一個(gè)FooAsyncActionInvoker實(shí)例。

默認(rèn)ActionInvoker類型:Artech.Mvc.FooAsyncActionInvoker

現(xiàn)在我們對(duì)NinjectDependencyResolver的定義稍加修改,將針對(duì)IAsyncActionInvoker接口的類型影射刪除,只保留針對(duì)IActionInvoker的映射。

public class NinjectDependencyResolver : IDependencyResolver  {      //其它成員      private void AddBindings()      {          this.Kernel.Bind<IActionInvoker>().To<FooActionInvoker>();          //this.Kernel.Bind<IAsyncActionInvoker>().To<FooAsyncActionInvoker>();      }  }

再次運(yùn)行我們的程序則會(huì)得到如下的輸出結(jié)果。由于NinjectDependencyResolver只能通過IActionInvoker接口提供具體的ActionInvoker,所以最終被創(chuàng)建的是一個(gè)FooActionInvoker對(duì)象。這個(gè)實(shí)例演示告訴我們:當(dāng)我們需要使用到自定義的ActionInvoker的時(shí)候,可以通過自定義DependencyResolver以IoC的方式提供具體的ActionInvoker實(shí)例。

默認(rèn)ActionInvoker類型:Artech.Mvc.FooActionInvoker

四、ControllerDescriptor的同步與異步

如果采用ControllerActionInvoker,Action總是以同步的方式來直接,但是當(dāng)AsyncControllerActionInvoker作為Controller的ActionInvoker時(shí),并不意味著總是以異步的方式來執(zhí)行所有的Action。至于這兩種類型的ActionInvoker具體采用對(duì)Action的怎樣的執(zhí)行方式,又涉及到兩個(gè)描述對(duì)象,即用于描述Controller和Action的ControllerDescriptor和ActionDescriptor。

通過前面“Model的綁定”中對(duì)這兩個(gè)對(duì)象進(jìn)行過相應(yīng)的介紹,我們知道在ASP.NET MVC應(yīng)用編程接口中具有兩個(gè)具體的ControllerDescriptor,即ReflectedControllerDescriptor和ReflectedAsyncControllerDescriptor,它們分別代表同步和異步版本的ControllerDescriptor。

public class ReflectedControllerDescriptor : ControllerDescriptor  {      //省略成員  }     public class ReflectedAsyncControllerDescriptor : ControllerDescriptor  {      //省略成員  }

ReflectedControllerDescriptor和ReflectedAsyncControllerDescriptor并非對(duì)分別實(shí)現(xiàn)了IController和IAyncController接口的Controller的描述,而是對(duì)直接繼承自抽象類Controller和AsyncController的Controller的描述。它們之間的區(qū)別在于創(chuàng)建者的不同,在默認(rèn)情況下ReflectedControllerDescriptor和ReflectedAsyncControllerDescriptor分別是通過ControllerActionInvoker和AsyncControllerActionInvoker來創(chuàng)建的。ActionInvoker和ControllerDescriptor之間的關(guān)系可以通過如下圖所示的UML來表示。

ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么

ActionInvoker與ControllerDescriptor之間的關(guān)系可以通過一個(gè)簡(jiǎn)單的實(shí)例來驗(yàn)證。在通過Visual Studio的ASP.NET MVC項(xiàng)目模板創(chuàng)建的空Web應(yīng)用中,我們自定義了如下兩個(gè)分別繼承自ControllerActionInvoker和AsyncControllerActionInvoker的ActionInvoker類型。在這兩個(gè)自定義ActionInvoker中,定義了公有的GetControllerDescriptor方法覆蓋了基類的同名方法(受保護(hù)的虛方法),并直接直接調(diào)用基類的同名方法根據(jù)提供的Controller上下文的到相應(yīng)的ControllerDescriptor對(duì)象。

 public class FooActionInvoker : ControllerActionInvoker   {        public new ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)       {           return base.GetControllerDescriptor(controllerContext);       }   }       public class BarActionInvoker : AsyncControllerActionInvoker  {      public new ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)      {          return base.GetControllerDescriptor(controllerContext);      }  }

然后我們定義了兩個(gè)Controller類型,它們均是抽象類型Controller的直接繼承者。如下面的代碼片斷所示,這兩Controller類(FooController和BarController)都重寫了虛方法CreateActionInvoker,而返回的ActionInvoker類型分別是上面我們定義的FooActionInvoker和BarActionInvoker。在默認(rèn)的Action方法Index中,我們利用當(dāng)前的ActionInvoker得到用于描述本Controller的ControllerDescriptor對(duì)象,并將其類型呈現(xiàn)出來。

 public class FooController : Controller   {       protected override IActionInvoker CreateActionInvoker()       {           return new FooActionInvoker();       }           public void Index()       {          ControllerDescriptor controllerDescriptor = ((FooActionInvoker)this.ActionInvoker).GetControllerDescriptor(ControllerContext);          Response.Write(controllerDescriptor.GetType().FullName);      }  }     public class BarController : Controller  {      protected override IActionInvoker CreateActionInvoker()      {          return new BarActionInvoker();      }         public void Index()      {          ControllerDescriptor controllerDescriptor = ((BarActionInvoker)this.ActionInvoker).GetControllerDescriptor(ControllerContext);          Response.Write(controllerDescriptor.GetType().FullName);      }  }

現(xiàn)在我們運(yùn)行我們的程序,并在瀏覽器中輸入相應(yīng)的地址對(duì)定義在FooController和BarController的默認(rèn)Action方法Index發(fā)起訪問,相應(yīng)的ControllerDescriptor類型名稱會(huì)以下圖所示的形式呈現(xiàn)出來,它們的類型分別是ReflectedControllerDescriptorReflectedAsyncControllerDescriptor。

ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么

五、ActionDescriptor的執(zhí)行

Controller包含一組用于描述Action方法的ActionDescriptor對(duì)象。由于Action方法可以采用同步和異步執(zhí)行方法,異步Action對(duì)應(yīng)的ActionDescriptor直接或者間接繼承自抽象類AsyncActionDescriptor,后者是抽象類ActionDescriptor的子類。如下面的代碼片斷所示,同步和異步Action的執(zhí)行分別通過調(diào)用Execute和BeginExecute/EndExecute方法來完成。值得一提的是,AsyncActionDescriptor重寫了Execute方法并直接在此方法中拋出一個(gè)InvalidOperationException異常,也就是說AsyncActionDescriptor對(duì)象只能采用 異步執(zhí)行方式。

 public abstract class ActionDescriptor : ICustomAttributeProvider   {       //其他成員       public abstract object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters);   }       public abstract class AsyncActionDescriptor : ActionDescriptor   {       //其他成員      public abstract IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state);      public abstract object EndExecute(IAsyncResult asyncResult);  }

通過前面“Model的綁定”我們知道,在ASP.NET MVC應(yīng)用編程接口中采用ReflectedControllerDescriptor來描述同步Action。異步Action方法具有兩種不同的定義方式:其一,通過兩個(gè)匹配的方法XxxAsync/XxxCompleted定義;其二,通過返回類型為Task的方法來定義。這兩種異步Action方法對(duì)應(yīng)的AsyncActionDescriptor類型分別是ReflectedAsyncActionDescriptor和TaskAsyncActionDescriptor。

對(duì)于ReflectedControllerDescriptor來說,包含其中的ActionDescriptor類型均為ReflectedActionDescriptor。而ReflectedAsyncControllerDescriptor描述的Controller可以同時(shí)包含同步和異步的Action方法,ActionDescriptor的類型取決于Action方法定義的方式。ControllerDescriptor與ActionDescriptor之間的關(guān)系如下圖所示的UML來表示。

ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么

實(shí)例演示:AsyncActionInvoker對(duì)ControllerDescriptor的創(chuàng)建

為了讓讀者對(duì)ActionInvoker對(duì)ControllerDescriptor的解析機(jī)制具有一個(gè)深刻的理解,同時(shí)也作為對(duì)該機(jī)制的驗(yàn)證,我們做一個(gè)簡(jiǎn)單的實(shí)例演示。通過前面的介紹我們知道在默認(rèn)的情況下Controller采用AsyncControllerActionInvoker進(jìn)行Action方法的執(zhí)行,這個(gè)例子就來演示一下它生成的ControllerDescriptor是個(gè)怎樣的對(duì)象。我們通過Visual Studio的ASP.NET MVC項(xiàng)目模板創(chuàng)建一個(gè)空Web應(yīng)用,并創(chuàng)建一個(gè)默認(rèn)的HomeController,然后對(duì)其進(jìn)行如下的修改。

public class HomeController : AsyncController  {      public void Index()      {          MethodInfo method = typeof(AsyncControllerActionInvoker).GetMethod("GetControllerDescriptor", BindingFlags.Instance | BindingFlags.NonPublic);          ControllerDescriptor controllerDescriptor = (ControllerDescriptor)method.Invoke(this.ActionInvoker, new object[] { this.ControllerContext });          Response.Write(controllerDescriptor.GetType().FullName + "<br/>");          CheckAction(controllerDescriptor, "Foo");          CheckAction(controllerDescriptor, "Bar");         CheckAction(controllerDescriptor, "Baz");      }      private void CheckAction(ControllerDescriptor controllerDescriptor,string actionName)     {         ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(this.ControllerContext, actionName);         Response.Write(string.Format("{0}: {1}<br/>",actionName,actionDescriptor.GetType().FullName));     }      public void Foo() { }     public void BarAsync() { }     public void BarCompleted() { }     public Task<ActionResult> Baz()     {         throw new NotImplementedException();     }

我們首先將HomeController的基類從Controller改為AsyncController,并定義了Foo、BarAsync/BarCompleted和Baz四個(gè)方法,我們知道它們對(duì)應(yīng)著Foo、Bar和Baz三個(gè)Action,其中Foo是同步Action,Bar和Baz分別是兩種不同定義形式(XxxAsync/XxxCompleted和Task)的異步Action。

CheckAction用于根據(jù)指定的Action名稱從ControllerDescriptor對(duì)象中獲取用于表示對(duì)應(yīng)Action的ActionDescriptor對(duì)象,最終將類型名稱呈現(xiàn)出來。在Index方法中,我們通過反射的方式調(diào)用當(dāng)前ActionInvoker(一個(gè)AsyncControllerActionInvoker對(duì)象)的受保護(hù)方法GetControllerDescriptor或者用于描述當(dāng)前Controller(HomeController)的ControllerDescriptor的對(duì)象,并將類型名稱呈現(xiàn)出來。最后通過調(diào)用CheckAction方法將包含在創(chuàng)建的ControllerDescriptor對(duì)象的三個(gè)ActionDescriptor類型呈現(xiàn)出來。

當(dāng)我們運(yùn)行該程序的時(shí)候,在瀏覽器中會(huì)產(chǎn)生如下的輸出結(jié)果,從中可以看出ControllerDescriptor類型為ReflectedAsyncControllerDescriptor。同步方法Foo對(duì)象的ActionDescriptor是一個(gè)ReflectedActionDescriptor對(duì)象;以XxxAsync/XxxCompleted形式定義的異步方法Bar對(duì)應(yīng)的ActionDescriptor是一個(gè)ReflectedAsyncActionDescriptor對(duì)象;而返回類型為Task的方法Baz對(duì)應(yīng)的ActionDescriptor類型則是TaskAsyncActionDescriptor。

ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么

AsyncController、AsyncControllerActionInvoker與AsyncActionDescriptor

不論我們采用哪種形式的定義方式,步Action方法都只能定義在繼承自AsyncController的Controller類型中,否則將被認(rèn)為是同步方法。此外,由于通過ControllerActionInvoker只能創(chuàng)建包含ReflectedActionDescriptor的ReflectedControllerDescriptor,如果我們?cè)贏syncController中采用ControllerActionInvoker對(duì)象作為ActionInvoker,所有的Action方法也將被認(rèn)為是同步的。

我們同樣可以采用一個(gè)簡(jiǎn)單的實(shí)例演示來證實(shí)這一點(diǎn)。在通過Visual Studio的ASP.NET MVC項(xiàng)目模板創(chuàng)建的空Web應(yīng)用中我們定義如下三個(gè)Controller(FooController、BarController和BazController)。我們重寫了它們的CreateActionInvoker方法,返回的ActionInvoker類型(FooActionInvoker和BarActionInvoker)定義在上面,在這里我們將FooActionInvoker和BarActionInvoker看成是ControllerActionInvoker和AsyncControllerActionInvoker(默認(rèn)使用的ActionInvoker)。

 public class FooController : AsyncController   {       protected override IActionInvoker CreateActionInvoker()       {           return new BarActionInvoker();       }       public void Index()       {           BarActionInvoker actionInvoker = (BarActionInvoker)this.ActionInvoker;          Utility.DisplayActions(controllerContext=>actionInvoker.GetControllerDescriptor(ControllerContext),ControllerContext);      }         public void DoSomethingAsync()      { }      public void DoSomethingCompleted()      { }  }     public class BarController : Controller  {      protected override IActionInvoker CreateActionInvoker()      {          return new BarActionInvoker();      }      public void Index()      {          BarActionInvoker actionInvoker = (BarActionInvoker)this.ActionInvoker;          Utility.DisplayActions(controllerContext => actionInvoker.GetControllerDescriptor(ControllerContext), ControllerContext);      }      public void DoSomethingAsync()      { }      public void DoSomethingCompleted()      { }  }     public class BazController : Controller  {      protected override IActionInvoker CreateActionInvoker()      {          return new FooActionInvoker();      }      public void Index()      {          FooActionInvoker actionInvoker = (FooActionInvoker)this.ActionInvoker;          Utility.DisplayActions(controllerContext => actionInvoker.GetControllerDescriptor(ControllerContext), ControllerContext);      }      public void DoSomethingAsync()      { }      public void DoSomethingCompleted()      { }  }     public static class Utility  {      public static void DisplayActions(Func<ControllerContext, ControllerDescriptor> controllerDescriptorAccessor, ControllerContext controllerContext)      {           ControllerDescriptor controllerDescriptor = controllerDescriptorAccessor(controllerContext);          string[] actionNames = { "DoSomething", "DoSomethingAsync", "DoSomethingCompleted" };          Array.ForEach(actionNames, actionName =>              {                  ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext,actionName);                  if (null != actionDescriptor)                  {                      HttpContext.Current.Response.Write(string.Format("{0}: {1}<br/>", actionDescriptor.ActionName, actionDescriptor.GetType().Name));                  }              });      }  }

我們?cè)谌齻€(gè)Controller中以異步Action的形式定義了兩個(gè)方法DoSomethingAsync和DoSomethingCompleted。FooController繼承自AsyncController,使用AsyncControllerActionInvoker作為其ActionInvoker,這是正常的定義;BarController雖然采用AsyncControllerActionInvoker,但是將抽象類Controller作為其基類;而BazController雖然繼承自ActionInvoker,但ActionInvoker類型為ControllerActionInvoker。在默認(rèn)的Action方法Index中,我們將通過DoSomethingAsync和DoSomethingCompleted方法定義的Action的名稱和對(duì)應(yīng)的ActionDescriptor類型輸出來。

如果我們運(yùn)行該程序,并在瀏覽器中輸入相應(yīng)的地址對(duì)定義在三個(gè)Controller的默認(rèn)Action方法Index發(fā)起訪問,會(huì)呈現(xiàn)出如下圖所示的結(jié)果。我們可以清楚地看到,對(duì)于以XxxAsync/XxxCompleted形式定義的“異步”Action方法定義,只有針對(duì)AsyncController并且采用AsyncControllerActionInvoker的情況下才會(huì)被解析為一個(gè)異步Action。如果不滿足這兩個(gè)條件,它們會(huì)被視為兩個(gè)普通的同步Action。

ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么

Action方法的執(zhí)行

目標(biāo)Action方法的最終執(zhí)行由被激活的Controller的ActionInvoker決定,ActionInvoker最終通過調(diào)用對(duì)應(yīng)的ActionDescriptor來執(zhí)行被它描述的Action方法。如果采用ControllerActionInvoker,被它創(chuàng)建的ControllerDescriptor(ReflectedControllerDescriptor)只包含同步的ActionDescriptor(ReflectedActionDescriptor),所以Action方法總是以同步的方式被執(zhí)行。

如果目標(biāo)Controller是抽象類Controller的直接繼承者,這也是通過Visual Studio的Controller創(chuàng)建向?qū)У哪J(rèn)定義方式,ActionInvoker(ControllerActionInvoker/AsyncControllerActionInvoker)的選擇只決定了創(chuàng)建的ControllerDescriptor的類型(ReflectedControllerDescriptor/ReflectedAsyncControllerDescriptor),ControllerDescriptor包含的所有ActionDescriptor依然是同步的(ReflectedActionDescriptor),所以Action方法也總是以同步的方式被執(zhí)行。

以異步方式定義的Action方法(XxxAsync/XxxCompleted或采用Task返回類型)只有定義在繼承自AsyncController的Controller類型中,并且采用AsyncControllerActionInvoker作為其ActionInvoker,最終才會(huì)創(chuàng)建AsyncActionDescriptor來描述該Action。也只有同時(shí)滿足這兩個(gè)條件,Action方法才能以異步的方式執(zhí)行。

看完上述內(nèi)容,你們掌握ASP.NET MVC涉及到的5個(gè)同步與異步分別是什么的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI