Aspnet MVC Asynchronous invocation

Source: Internet
Author: User

A schematic to describe the asynchronous invocation under the ASPNET MVC

  {Request}   /    \-------ISS-------> work thread  |        |       \  Route- aysn controller  |          |          \ [invoke] CLR thread pool   |         /  |        /  |       /complete-   asyncmanager   |      /  


From the schematic you can see:
The user sends the request, the server routes to the controller, the controller to the Action,action internal calls the new thread through the thread pool to execute the request, and then returns the data to the user.


This diagram involves a property of the controller Asyncmanager
The role of Asyncmanagerde is mainly reflected in two points:
1. Identify the start and end of asynchronous, by Asyncmanager.outstandingoperations.increment/outstandingoperations.decrement
2. In the execution of the thread to the end of the callback process parameters passed through Asyncmanager.parameters (type is a dictionary, pass parameters need to note that key needs to be consistent with the parameter name of the result parameter callback).

Asyncmanager is not required in an asynchronous invocation.

Asynchronous is good, but not all occasions are suitable, in general, if there is no long time and distribution of demand, asynchronous is not required

There are three ways of implementing asynchronous operations in ASPNET MVC:

1. Through the asynchronous controller Asynccontroller
The custom controller defines the action in the xxxasync/xxxcompleted format internally by inheriting Asynccontroller, for example:

 Public void Indexasync () {}  Public ActionResult indexcompleted (string  parameter); // one of the parameters in indexcompleted parameter // pass through asyncmanager.parameters ["parameter '] = XX // parameter name and key to maintain consistency

Async and completed definitions are always paired, and the async-defined methods are used to perform asynchronous operations, and completed-defined methods are used to return the results.

With the method defined by Xxasync and xxcompeleted, the ASPNET MVC is not called asynchronously at the time of invocation, so the real work still requires us to define asynchronous operations in our own async. A simple example:

     Public classCustomasynccontroller:asynccontroller { Public voidIndexasync () {//increment Default count is 1 if no parameter is written//if more than one task is present, you need to add the corresponding count value to ensure that the result returns correctlyAsyncManager.OutstandingOperations.Increment (); Task.Factory.StartNew (()=           {               intsum =0;  for(inti =0; I <10000000; i++) {sum + =i;} //passing parameters to xxxcompletedasyncmanager.parameters["sum"] =sum; //EndAsyncManager.OutstandingOperations.Decrement ();//multiple tasks are called multiple times, and the number of calls is generally equal to the count set in increment           }); }         PublicActionResult indexcompleted (stringsum) {            returnContent (sum.        ToString ()); }    }
View Code

2. Through the async and await keywords

The Async/await keyword is used to identify asynchronous operations, and we use a simple example to demonstrate the use of async/await

A. Example we first define a WEBAPI to return the user information

B. Through the service class, asynchronous calls use the Webapi interface to return user information

C. Controller call service class returns data results

     Public class Usercontroller:apicontroller    {        privatestaticnew  userrepository ();        [System.Web.Http.HttpGet]          Public Ilist<usermodel> GetAll ()        {            return  _respository. GetAll ();        }    }
    Public classUserService {Private StaticUserService instance =NULL;  Public Staticuserservice Instance {Get            {                if(Instance = =NULL) Instance=NewUserService (); returninstance; }        }         Public AsyncTask<ilist<usermodel>> Getusersasync (CancellationToken token =default(CancellationToken)) {            varURI ="Http://localhost:3541/api/user/getall"; using(HttpClient client =NewHttpClient ()) {                varResponse =awaitclient.                Getasync (URI); return awaitResponse. Content.readasasync<ilist<usermodel>>(); }        }    }
     Public class Customcontroller:controller    {       publicasync task<actionresult> Index ()        {             await UserService.Instance.GetUsersAsync ();             return Json (models,jsonrequestbehavior.allowget);        }    }

3. Asynchronous by returning a task directly

The simplest and most direct way.

     Public classHomecontroller:asynccontroller { PublicTask<actionresult>Index () {returnTask.Factory.StartNew (() =           {               return NewList<usermodel>               {                    NewUsermodel {Name ="Visonme" },                    NewUsermodel {Name ="visonme2" }               }; }). ContinueWith<ActionResult> (Task) =           {               returnJson (Task.           Result, Jsonrequestbehavior.allowget);        }); }    }

Aspnet MVC Asynchronous invocation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.