Explore the little-known Mysteries of ASP (2): Work with the Entity Framework to get asynchronous throughout

Source: Internet
Author: User

Why

In the application, especially in the Internet application, the performance has been a lot of large web sites, due to the advent of the Web2.0 era, people more applications from the C/s structure to the B/s structure, which will bring the client light, deployment, try convenient and efficient advantages, but everything has his two sides, This trend also brings other convenient bad effects, one of the most important is the system to the server performance requirements, with the increase in user volume and system functions, the server performance gradually become a short board.

The impact of this performance, can be optimized from many aspects, such as the use of load-balanced server, set up a server cluster, etc., but this is from the hardware configuration optimization, and in software development, also can do a lot of performance optimization.

As we all know, Microsoft's IIS server has a limited number of threads per thread, and in previous ASP. NET MVC applications, when a request arrives at the server, IIS creates a thread from the thread pool to start the call, and when all the operations are done, the request is returned, the thread is freed, That is to say, the thread is held during the entire call.

However, if the number of program visitors increases, the thread becomes a scarce resource, if in a single request, the need to access the remote database, or large IO processing, this is the request is likely to hold a thread for a long time, and when the large number of users this long-term request, the thread pool will be quickly full, The request enters the wait queue, and the wait queue has the maximum length, and it is possible to return the request timeout to the browser side.

So, we would like to need an asynchronous way to execute the request, when a long request is encountered, the request is sent from the IIS thread to the background thread, the current thread is disposed, the processing completes, and then the thread pool is selected to proceed with the additional processing of the request.

How

In the case of ASP. MVC3, the Asynccontroller has been provided to create an asynchronous controller that can be processed using the async and completed method pairs, and now We do not need to implement classes that inherit from Asynccontroller alone, and you can create an asynchronous controller simply by adding a specific keyword and return type to the original action method.

Also, in entity Framework6, the asynchronous querying and saving of data is implemented, which allows us to process logic asynchronously in the application process.

Let's Do it

Example using VS2013 to create an ASP. MVC5 project "Asyncexample" (not obsessed with design principles, note the focus)

Add a user class in the Models folder:

namespace asyncexample.models{    publicclass  User    {        [Key]        public  intgetset;}          Public string Get Set ; }          Public string Get Set ; }    }}

Add a reference to the Entity Framework for a project

Pm> Install-package EntityFramework

To create the DbContext subclass Asyncdbcontext class:

namespace asyncexample.models{    publicclass  asyncdbcontext:dbcontext    {          Public Get Set ; }          Public asyncdbcontext ()             Base ("name=defaultconnection")        {                 }    }}

Update Web. config to add a database connection string.

To open the migrations function of the Entity Framework:

Pm> enable-migrations

BTW: In the new version of the Entity Framework, you can already use automatic migration, do not need to manually upgrade the database structure for each model change, open the method is simple:

Open the Migrations folder under the Configuration.cs file, in the configuration default constructor can see a automaticmigrationsenabled property is set to False, change to true can automatically migrate, tremble

After the database has been updated, create a controller:

usingSystem.Data.Entity;namespaceasyncexample.controllers{ Public classUsercontroller:controller {asyncdbcontext context=NewAsyncdbcontext ();  PublicActionResult Create () {returnView (); } [HttpPost] Public AsyncTask<actionresult>Create (User user) {context.            Users.add (user); awaitcontext.            Savechangesasync (); returnRedirecttoaction ("List"); }         Public AsyncTask<actionresult>List () {returnView (awaitcontext.        Users.tolistasync ()); }    }}

As you can see in the Create and list two methods, both async and aswait have been used in creating two async methods, and we have only inherited the controller directly, because now synchronous asynchronous functions are put in this class, At the same time we need to introduce the Systen.Data.Entity namespace, which contains the Tolistasync extension method for the IQueryable type, which adds the function of asynchronous loading.

The final rendering effect, the plot of the floor:

This article is here, in fact, this series of the next article is not sure what content to write, I hope Bo Friends of friends to give some advice.

If you think this article is useful to you, please give a praise!

If you think this article may swim for others, please recommend one!

If you think this article is really nonsense, then you gave me a number of visits!

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.