欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解ASP.NET MVC下的异步Action的定义和执行原理

程序员文章站 2022-11-14 11:36:37
visual studio提供的controller创建向导默认为我们创建一个继承自抽象类controller的controller类型,这样的controller只能定义...

visual studio提供的controller创建向导默认为我们创建一个继承自抽象类controller的controller类型,这样的controller只能定义同步action方法。如果我们需要定义异步action方法,必须继承抽象类asynccontroller。这篇问你讲述两种不同的异步action的定义方法和底层执行原理。

一、基于线程池的请求处理

asp.net通过线程池的机制处理并发的http请求。一个web应用内部维护着一个线程池,当探测到抵达的针对本应用的请求时,会从池中获取一个空闲的线程来处理该请求。当处理完毕,线程不会被回收,而是重新释放到池中。线程池具有一个线程的最大容量,如果创建的线程达到这个上限并且所有的线程均被处于“忙碌”状态,新的http请求会被放入一个请求队列以等待某个完成了请求处理任务的线程重新释放到池中。

我们将这些用于处理http请求的线程称为工作线程(worker thread),而这个县城池自然就叫做工作线程池。asp.net这种基于线程池的请求处理机制主要具有如下两个优势:

  • 工作线程的重用:创建线程的成本虽然不如进程的激活,却也不是一件“一蹴而就”的事情,频繁地创建和释放线程会对性能造成极大的损害。而线程池机制避免了总是创建新的工作线程来处理每一个请求,被创建的工作线程得到了极大地重用,并最终提高了服务器的吞吐能力。
  • 工作线程数量的限制:资源的有限性具有了服务器处理请求的能力具有一个上限,或者说某台服务器能够处理的请求并发量具有一个临界点,一旦超过这个临界点,整台服务将会因不能提供足够的资源而崩溃。由于采用了对工作线程数量具有良好控制的线程池机制,asp.net mvc并发处理的请求数量不可能超过线程池的最大允许的容量,从而避免了在高并发情况下工作线程的无限制创建而最导致整个服务器的崩溃。

如果请求处理操作耗时较短,那么工作线程处理完毕后可以及时地被释放到线程池中以用于对下一个请求的处理。但是对于比较耗时的操作来说,意味着工作线程将被长时间被某个请求独占,如果这样的操作访问比较频繁,在高并发的情况下意味着线程池中将可能找不到空闲的工作线程用于及时处理最新抵达请求。

如果我们采用异步的方式来处理这样的耗时请求,工作线程可以让后台线程来接手,自己可以及时地被释放到线程池中用于进行后续请求的处理,从而提高了整个服务器的吞吐能力。值得一提的是,异步操作主要用于i/o绑定操作(比如数据库访问和远程服务调用等),而非cpu绑定操作,因为异步操作对整体性能的提升来源于:当i/o设备在处理某个任务的时候,cpu可以释放出来处理另一个任务。如果耗时操作主要依赖于本机cpu的运算,采用异步方法反而会因为线程调度和线程上下文的切换而影响整体的性能。

二、两种异步action方法的定义

在了解了在asynccontroller中定义异步action方法的必要性之后,我们来简单介绍一下异步action方法的定义方式。总的来说,异步action方法具有两种定义方式,一种是将其定义成两个匹配的方法xxxasync/xxxcompleted,另一种则是定义一个返回类型为task的方法。

xxxasync/xxxcompleted

如果我们使用两个匹配的方法xxxasync/xxxcompleted来定义异步action,我们可以将异步操作实现在xxxasync方法中,而将最终内容的呈现实现在xxxcompleted方法中。xxxcompleted可以看成是针对xxxasync的回调,当定义在xxxasync方法中的操作以异步方式执行完成后,xxxcompleted方法会被自动调用。xxxcompleted的定义方式和普通的同步action方法比较类似。

作为演示,我在如下一个homecontroller中定义了一个名为article的异步操作来呈现指定名称的文章内容。我们将指定文章内容的异步读取定义在articleasync方法中,而在articlecompleted方法中讲读取的内容以contentresult的形式呈现出来。

public class homecontroller : asynccontroller
   {
     public void articleasync(string name)
     {
       asyncmanager.outstandingoperations.increment();
       task.factory.startnew(() =>
         {
           string path = controllercontext.httpcontext.server.mappath(string.format(@"\articles\{0}.html", name));
           using (streamreader reader = new streamreader(path))
          {
            asyncmanager.parameters["content"] = reader.readtoend();
          }
          asyncmanager.outstandingoperations.decrement();
        });
    }
    public actionresult articlecompleted(string content)
    {
      return content(content);
    }
  } 

对于以xxxasync/xxxcompleted形式定义的异步action方法来说,asp.net mvc并不会以异步的方式来调用xxxasync方法,所以我们需要在该方法中自定义实现异步操作的执行。在上面定义的articleasync方法中,我们是通过基于task的并行编程方式来实现对文章内容的异步读取的。当我们以xxxasync/xxxcompleted形式定义的异步action方法的时候,会频繁地使用到controller的asyncmanager属性,该属性返回一个类型为asyncmanager对象,我们将在下面一节对其进行单独讲述。

在上面提供的实例中,我们在异步操作开始和结束的时候调用了asyncmanager的outstandingoperations属性的increment和decrement方法对于asp.net mvc发起通知。此外,我们还利用asyncmanager的parameters属性表示的字典来保存传递给articlecompleted方法的参数,参数在字典中的key(content)与articlecompleted的参数名称是匹配的,所以在调用方法articlecompleted的时候,通过asyncmanager的parameters属性指定的参数值将自动作为对应的参数值。

task返回值

如果采用上面的异步action定义方式,意味着我们不得不为一个action定义两个方法,实际上我们可以通过一个方法来完成对异步action的定义,那就是让action方法返回一个代表异步操作的task对象。上面通过xxxasync/xxxcompleted形式定义的异步action可以采用如下的定义方式。

 public class homecontroller asynccontroller
   {
     public task<actionresult> article(string name)
     {
       return task.factory.startnew(() =>
         {
           string path = controllercontext.httpcontext.server.mappath(string.format(@"\articles\{0}.html", name));
           using (streamreader reader = new streamreader(path))
           {
            asyncmanager.parameters["content"] = reader.readtoend();
          }
        }).continuewith<actionresult>(task =>
          {
            string content = (string)asyncmanager.parameters["content"];
            return content(content);
          });
    }
  }

上面定义的异步action方法article的返回类型为task<actionresult>,我们将异步文件内容的读取体现在返回的task对象中。对文件内容呈现的回调操作则通过调用该task对象的continuewith<actionresult>方法进行注册,该操作会在异步操作完成之后被自动调用。

如上面的代码片断所示,我们依然利用asyncmanager的parameters属性实现参数在异步操作和回调操作之间的传递。其实我们也可以使用task对象的result属性来实现相同的功能,article方法的定义也改写成如下的形式。

 public class homecontroller asynccontroller
   {
     public task<actionresult> article(string name)
     {
       return task.factory.startnew(() =>
         {
           string path = controllercontext.httpcontext.server.mappath(string.format(@"\articles\{0}.html", name));
           using (streamreader reader = new streamreader(path))
           {
            return reader.readtoend();
          }
        }).continuewith<actionresult>(task =>
          {          
            return content((string)task.result);
          });
    }
  }

三、asyncmanager

在上面演示的异步action的定义中,我们通过asyncmanager实现了两个基本的功能,即在异步操作和回调操作之间传递参数和向asp.net mvc发送异步操作开始和结束的通知。由于asyncmanager在异步action场景中具有重要的作用,我们有必要对其进行单独介绍,下面是asyncmanager的定义。

 public class asyncmanager
   {  
     public asyncmanager();
     public asyncmanager(synchronizationcontext synccontext);
   
     public eventhandler finished;
   
     public virtual void finish();
     public virtual void sync(action action);
    
    public operationcounter outstandingoperations { get; }
    public idictionary<string, object> parameters { get; }
    public int timeout { get; set; }
  }
   
  public sealed class operationcounter
  {
    public event eventhandler completed;  
    
    public int increment();
    public int increment(int value);
    public int decrement();
    public int decrement(int value);
    
    public int count { get; }
  }

如上面的代码片断所示,asyncmanager具有两个构造函数重载,非默认构造函数接受一个表示同步上下文的synchronizationcontext对象作为参数。如果指定的同步上下文对象为null,并且当前的同步上下文(通过synchronizationcontext的静态属性current表示)存在,则使用该上下文;否则创建一个新的同步上下文。该同步上下文用于sync方法的执行,也就是说在该方法指定的action委托将会在该同步上下文中以同步的方式执行。

asyncmanager的核心是通过属性outstandingoperations表示的正在进行的异步操作计数器,该属性是一个类型为operationcounter的对象。操作计数通过只读属性count表示,当我们开始和完成异步操作的时候分别调用increment和decrement方法作增加和介绍计数操作。increment和decrement各自具有两个重载,作为整数参数value(该参数值可以是负数)表示增加或者减少的数值,如果调用无参方法,增加或者减少的数值为1。如果我们需要同时执行多个异步操作,则可以通过如下的方法来操作计数器。

 asyncmanager.outstandingoperations.increment(3);
   
   task.factory.startnew(() =>
   {
     //异步操作1
     asyncmanager.outstandingoperations.decrement();
   });
   task.factory.startnew(() =>
   {
    //异步操作2
    asyncmanager.outstandingoperations.decrement();
  });
  task.factory.startnew(() =>
  {
    //异步操作3
    asyncmanager.outstandingoperations.decrement();
  });

对于每次通过increment和decrement方法调用引起的计数数值的改变,operationcounter对象都会检验当前计数数值是否为零,如果则表明所有的操作运行完毕,如果预先注册了completed事件,该事件会被触发。值得一提的时候,表明所有操作完成执行的标志是计数器的值等于零,而不是小于零,如果我们通过调用increment和decrement方法使计数器的值称为一个负数,注册的completed事件是不会被触发的。

asyncmanager在初始化的时候就注册了通过属性outstandingoperations表示的operationcounter对象的completed事件,使该事件触发的时候调用自身的finish方法。而虚方法finish在asyncmanager中的默认实现又会触发自身的finished事件。

如下面的代码片断所示,controller类实现了iasyncmanagercontainer接口,而后者定义了一个只读属性asyncmanager用于提供辅助执行异步action的asyncmanager对象,而我们在定义异步action方法是使用的asyncmanager对象就是从抽象类controller中集成下来的asyncmanager属性。

  public abstract class controller controllerbase, iasyncmanagercontainer,...
   {
     public asyncmanager asyncmanager { get; }
   }
   
   public interface iasyncmanagercontainer
   {  
     asyncmanager asyncmanager { get; }
   }

四、completed方法的执行

对于通过xxxasync/xxxcompleted形式定义的异步action,我们说回调操作xxxcompleted会在定义在xxxasync方法中的异步操作执行结束之后被自动调用,那么xxxcompleted方法具体是如何被执行的呢?

异步action的执行最终是通过描述该action的asyncactiondescriptor对象的beginexecute/endexecute方法来完成的。通过之前“model的绑定”的介绍我们知道通过xxxasync/xxxcompleted形式定义的异步action通过一个reflectedasyncactiondescriptor对象来表示的,reflectedasyncactiondescriptor在执行beginexecute方法的时候会注册controller对象的asyncmanager的finished事件,使该事件触发的时候去执行completed方法。

也就是说针对当前controller的asyncmanager的finished事件的触发标志着异步操作的结束,而此时匹配的completed方法会被执行。由于asyncmanager的finish方法会主动触发该事件,所以我们可以通过调用该方法使completed方法立即执行。由于asyncmanager的operationcounter对象的completed事件触发的时候会调用finish方法,所以当表示当前正在执行的异步操作计算器的值为零时,completed方法也会自动被执行。

如果我们在xxxasync方法中通过如下的方式同时执行三个异步操作,并在每个操作完成之后调用asyncmanager的finish方法,意味着最先完成的异步操作会导致xxxcompleted方法的执行。换句话说,当xxxcompleted方法执行的时候,可能还有两个异步操作正在执行。

  asyncmanager.outstandingoperations.increment(3);
   
   task.factory.startnew(() =>
   {
     //异步操作1
     asyncmanager.finish();
   });
   task.factory.startnew(() =>
   {
    //异步操作2
    asyncmanager.finish();
  });
  task.factory.startnew(() =>
  {
    //异步操作3
    asyncmanager.finish();
  });

如果完全通过为完成的异步操作计数机制来控制xxxcompleted方法的执行,由于计数的检测和completed事件的触发只发生在operationcounter的increment/decrement方法被执行的时候,如果我们在开始和结束异步操作的时候都没有调用这两个方法,xxxcompleted是否会执行呢?同样以之前定义的用语读取/显示文章内容的异步action为例,我们按照如下的方式将定义在articleasync方法中针对asyncmanager的outstandingoperations属性的increment和decrement方法调用注释调用,articlecompleted方法是否还能正常运行呢?

  public class homecontroller asynccontroller
   {
     public void articleasync(string name)
     {
       //asyncmanager.outstandingoperations.increment();
       task.factory.startnew(() =>
         {
           string path = controllercontext.httpcontext.server.mappath(string.format(@"\articles\{0}.html", name));
           using (streamreader reader = new streamreader(path))
          {
            asyncmanager.parameters["content"] = reader.readtoend();
          }
          //asyncmanager.outstandingoperations.decrement();
        });
    }
    public actionresult articlecompleted(string content)
    {
      return content(content);
    }
  }

实际上articlecompleted依然会被执行,但是这样我们就不能确保正常读取文章内容,因为articlecompleted方法会在articleasync方法执行之后被立即执行。如果文章内容读取是一个相对耗时的操作,表示文章内容的articlecompleted方法的content参数在执行的时候尚未被初始化。在这种情况下的articlecompleted是如何被执行的呢?

原因和简单,reflectedasyncactiondescriptor的beginexecute方法在执行xxxasync方法的前后会分别调用asyncmanager的outstandingoperations属性的increment和decrement方法。对于我们给出的例子来说,在执行articleasync之前increment方法被调用使计算器的值变成1,随后articleasync被执行,由于该方法以异步的方式读取指定的文件内容,所以会立即返回。最后decrement方法被执行使计数器的值变成0,asyncmanager的completed事件被触发并导致articlecompleted方法的执行。而此时,文件内容的读取正在进行之中,表示文章内容的content参数自然尚未被初始化。

reflectedasyncactiondescriptor这样的执行机制也对我们使用asyncmanager提出了要求,那就是对尚未完成的一步操作计数器的增加操作不应该发生在异步线程中,如下所示的针对asyncmanager的outstandingoperations属性的increment方法的定义是不对的。

  public class homecontroller asynccontroller
   {
     public void xxxasync(string name)
     {
       task.factory.startnew(() =>
         {
           asyncmanager.outstandingoperations.increment();
            //...
            asyncmanager.outstandingoperations.decrement();
        });
    }
    //其他成员
  } 

下面采用正确的定义方法:

 public class homecontroller asynccontroller
   {
     public void xxxasync(string name)
    {
      asyncmanager.outstandingoperations.increment();
       task.factory.startnew(() =>
         {
           //...
           asyncmanager.outstandingoperations.decrement();
        });
    }
    //其他成员
  } 

最后再强调一点,不论是显式调用asyncmanager的finish方法,还是通过调用asyncmanager的outstandingoperations属性的increment方法是计数器的值变成零,仅仅是让xxxcompleted方法得以执行,并不能真正阻止异步操作的执行。

五、异步操作的超时控制

异步操作虽然适合那些相对耗时的i/o绑定型操作,但是也并不说对一步操作执行的时间没有限制。异步超时时限通过asyncmanager的整型属性timeout表示,它表示超时时限的总毫秒数,其默认值为45000(45秒)。如果将timeout属性设置为-1,意味着异步操作执行不再具有任何时间的限制。对于以xxxasync/xxxcompleted形式定义的异步action来说,如果xxxasync执行之后,在规定的超时时限中xxxcompleted没有得到执行,一个timeoutexception会被抛出来。

如果我们以返回类型为task的形式定义异步action,通过task体现的异步操作的执行时间不受asyncmanager的timeout属性的限制。我们通过如下的代码定义了一个名为data的异步action方法以异步的方式获取作为model的数据并通过默认的view呈现出来,但是异步操作中具有一个无限循环,当我们访问该data方法时,异步操作将会无限制地执行下去,也不会有timeoutexception异常发生。

  public class homecontroller asynccontroller
   {
     public task<actionresult> data()
     {
       return task.factory.startnew(() =>
       {
         while (true)
         { }
         return getmodel();
          
      }).continuewith<actionresult>(task =>
      {
        object model = task.result;
        return view(task.result);
      });
    }
    //其他成员
  }

在asp.net mvc应用编程接口中具有两个特殊的特性用于定制异步操作执行的超时时限,它们是具有如下定义的asynctimeoutattribute和noasynctimeoutattribute,均定义在命名空间system.web.mvc下。

  [attributeusage(attributetargets.method | attributetargets.class, inherited=true, allowmultiple=false)]
   public class asynctimeoutattribute actionfilterattribute
   {
     
     public asynctimeoutattribute(int duration);
     public override void onactionexecuting(actionexecutingcontext filtercontext);  
     public int duration { get; }
   }
   
  [attributeusage(attributetargets.method | attributetargets.class, inherited=true, allowmultiple=false)]
  public sealed class noasynctimeoutattribute asynctimeoutattribute
  {
    // methods
    public noasynctimeoutattribute() base(-1)
    {
    }
  }

从上面给出的定义我们可以看出这两个特性均是actionfilter。asynctimeoutattribute的构造函数接受一个表示超时时限(以毫秒为单位)的整数作为其参数,它通过重写onactionexecuting方法将指定的超时时限设置给当前controller的asyncmanager的timeout属性进行。noasynctimeoutattribute是asynctimeoutattribute的继承者,它将超时时限设置为-1,意味着它解除了对超时的限制。

从应用在这两个特性的attributeusageattribute定义可看出,它们既可以应用于类也可以用于也方法,意味着我们可以将它们应用到controller类型或者异步action方法(仅对xxxasync方法有效,不能应用到xxxcompleted方法上)。如果我们将它们同时应用到controller类和action方法上,针对方法级别的特性无疑具有更高的优先级。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。