Using asynchronous controllers in ASP. NET MVC EF

Source: Internet
Author: User

Recently realized a truth, here to share to everyone: education represents your past, the ability to represent your present, study represents your future.

10 years Hedong 10 years hexi, MO bullying Juvenile poor

Lifelong Learning, Excellence

Why use an asynchronous operation/thread pool

Why is it necessary to use async in ASP. IIS has a thread pool to handle the user's request, and when a new request comes in, the thread in the pool is dispatched to handle the request, however, when the concurrency is high, the threads in the pool are not able to meet so many requests. Each thread in the pool is in a busy state when the request is processed and the thread that processes the request is blocked, and the thread cannot service another request, and if the request queue is full, the WEB server rejects the request and is in an HTTP 503 busy state. If you are dealing with some high latency, such as a network operation, most of these threads just wait for the state to do nothing for most of the time, so that the thread can use asynchronous programming to make better use of it.

Asynchronous processing

For example , if a request generates a network call that takes two seconds to complete, it takes two seconds for the request to execute synchronously or asynchronously. However, during an asynchronous call, the server does not block the response to other requests while waiting for the first request to complete. Therefore, when there are many requests to invoke a long-running operation, an asynchronous request can prevent the request from queuing up. The maximum thread pool in. NET 4.5 has also added await and async keywords in the. NET 4.5 to simplify asynchronous programming.

Synchronous or asynchronous (excerpt from MSDN)

Typically, you use a synchronization pipeline when the following conditions are true:

    • The operation is simple or has a short running time.

    • Simplicity is more important than efficiency.

    • This operation is primarily a CPU operation rather than an operation that contains a large amount of disk or network overhead. The use of asynchronous operation methods on CPU bound operations does not provide any benefit and also results in more overhead.

Typically, you use an asynchronous pipeline when the following conditions are true:

    • Operations are network-bound or I/O-bound rather than CPU-bound.

    • Testing shows that blocking operations are a bottleneck for site performance and that IIS can service more requests by using asynchronous action methods for these blocking calls.

    • Parallelism is more important than the simplicity of the code.

    • You want to provide a mechanism for users to cancel long-running requests.

Using asynchronous controllers in ASP.

#region1. Asynchronous request[AsyncTimeout ( +)]         Public AsyncTask<actionresult>Index () {vardata =awaitGetpagetaskasync ("http://163.com"); returndata; }         Public AsyncTask<actionresult> Getpagetaskasync (stringURL) {            Try            {                using(varClient =NewHttpClient ()) {                    awaitTask.delay ( the); varFetchtexttask =client.                    Getstringasync (URL); returnJson (New{Fetchtext =awaitFetchtexttask,error="NO"},jsonrequestbehavior.allowget); }            }            Catch(WebException ex) {Throwex; }        }        #endregion

The following is an example of EF:

The highlights in the code show the difference between the Async method and the synchronization method:

         Public Async task<actionresult> Index ()        {            var departments = db. Departments.include (d = d.administrator);             return View (await  departments.  Tolistasync());        }

We applied four changes to enable the Entity Framework database to execute an asynchronous query:

    • The method uses the Async keyword, which tells the compiler to generate a portion of the body of the callback method and automatically creates a task<actionresult> return object.
    • The return type changes from ActionResult to task<actionresult>. The task<t> type indicates that the task in progress has a result of type T.
    • The await keyword is applied to the Web service invocation. When the compiler sees this keyword, the method is divided into two parts in the background. The first part ends with the asynchronous operation starting, and the second part is put into a callback method when the operation completes.
    • An asynchronous version of the ToList extension method was called.

Why only modify departments. ToList statement instead of Departments= db. Departments statement? The reason is that only queries or statements executed by the sent database can use asynchronous execution. Departments=db. The Departments statement sets a query, but the query is not executed until the ToList method is called. Therefore, only the ToList method is executed asynchronously.

In the details method and the edit and delete methods of HttpGet, the Find method is the method that causes the query to be sent to the database for retrieval, so the method can be executed asynchronously.

 Public Async task<actionresult>Details (int?ID) {if(id = =NULL)            {                return NewHttpstatuscoderesult (httpstatuscode.badrequest); } Department Department=awaitdb. Departments. Findasync            (ID); if(Department = =NULL)            {                returnHttpnotfound (); }            returnView (department); }

In the Create,httppost Edit and Deleteconfirmed methods, it is the SaveChanges method that causes the command to execute, rather like db. The Department.add (Department) method simply causes the entity to modify in memory.

 Public Async task<actionresult>Create ([Bind (include="Departmentid,name,budget,startdate,instructorid")] Department Department) {if(modelstate.isvalid) {db.                Departments.add (department); await db.                Savechangesasync (); returnRedirecttoaction ("Index"); } Viewbag.instructorid=NewSelectList (db. Instructors,"ID","LastName", department.            Instructorid); returnView (department); }

The program runs normally, just like any other controller. In this controller, however, all SQL queries are executed asynchronously.

Some things to note when you use asynchronous programming in the Entity Framework:

    • Async code is not thread-safe. In other words, do not use the same context instance to perform multiple operations in parallel.
    • If you want to take advantage of the performance benefits of asynchronous code, make sure that any library packages that you are using (such as paging), database queries that are made in the package, and so on, also use asynchronous execution.

@ Chen Wolong's blog

Using asynchronous controllers in ASP. NET MVC EF

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.