Some suggestions for building high-performance ASP. NET application for senior developers

Source: Internet
Author: User
Tags net thread

  • Load testing of applications in the early stages
  • Using the high-performance class library
  • Is your application CPU-intensive or IO-intensive?
  • Use the task-based asynchronous model, but be cautious
  • Distribution cache and session (session) state
  • Create Web Gardens
  • Cleverly using caching and lazy loading
  • Do not put C # code in the MVC view
  • Use fire & Forget when appropriate
  • Create for x64 CPU
  • Using the monitoring and diagnostic tools on the server
  • Analysis of applications in operation

If you're building a public-facing web site, what you want to accomplish at the end of the project is that the Web payload is performing well. This means that you want to make sure that your product runs under high load (50 concurrent users or 200 users per second, etc.), even if you don't think there's a load at this point. Over time, your Web site may attract more and more users, and if the load on the web is unbearable, then the natural web site starts to go downhill, which means customer churn and reputational damage.

So what can be done to make an ASP. NET or ASP. NET MVC application more performant?

Load testing of applications in the early stages

Most developers tend to load test after the integration test and regression test pass after application development is complete. Although it is better to perform a load test once the development is complete, it is too late to fix the performance problem once the code has been written. The most common example of this problem is that when an application does not respond properly to a load test, it considers scaling out (adding more servers). Sometimes this is not possible because the code is not suitable for implementing the extension server. For example, it is impossible to add more web nodes or worker processes when objects are stored in the session and are not serializable. If you find that your application may be deployed to multiple servers in the early stages of development, you should make the test environment and the final environment as close as possible to the number of configurations and servers, so your code will be easier to adapt.

Using the high-performance class library

I recently found a hot issue in my code when diagnosing performance issues with Web sites: JSON information from a third-party Web service must be deserialized multiple times. The JSON information is deserialized by Newtonsoft.json and proves that Newtonsoft.json is not the fastest class library when deserializing, and then we use a faster class library (such as servicestack) to replace json.net and get better results.

If we completed the load test in the early stages of picking up json.net as a serialized class library, we would have discovered performance problems earlier, and we would have no need to make so many changes in the code and not have to re-test it completely again.

Is your application CPU-intensive or IO-intensive?

One of the first things to consider when starting to implement Web applications and design projects is whether your application is CPU-intensive or IO-intensive? This is important for understanding the strategy of extending the application.

For example, if your application is CPU intensive, then you might want to use synchronous mode, parallel processing, and so on. However, for a product with many IO-constrained operations, such as with external Web services or network resources such as database communications, the task-based Asynchronous pattern may be more helpful for scaling out. In addition, to be able to create Web gardens and Web Farms someday, you might want to have a centralized caching system that implements the load across multiple worker processes or services.

Use the task-based asynchronous model, but be cautious

If your product relies on many IO-constrained operations, or if you include long-running operations that might need to consume valuable IIS threads waiting for an operation to complete, you might want to consider using the task-based Asynchronous Pattern for the ASP.

There are many manuals on the internet for asynchronous ASP. NET MVC actions (such as this ), so this blog tries to avoid introducing knowledge points about asynchrony. However, it must be noted that the traditional synchronous action in ASP. NET (MVC) causes the IIS thread to be busy until the operation completes or the request is processed. This means that if the Web app waits for an external resource (such as a Web service) to respond, then that thread will be busy: The number of threads in the net thread pool that can be used to process requests is also limited, so it is important to release the threads as quickly as possible. The task-based asynchronous action or method frees the thread after the request is processed, then gets the new thread from the thread pool and returns the result of the action using the new thread. In this way, multiple requests can be processed by multiple threads, which will give your app a better response.

Although tap mode is convenient for the right application, it must be used with caution. When you use tap design or implement a project, you have to pay attention to a few points (you can click here to see ), however, the biggest challenge for developers to use the async and await keywords is to know that in this context they have to handle threads slightly differently. For example, you can create a method that returns a task (such as task Product, the markdown of the blog Park does not support single angle brackets), and usually you can call the run () method on that task or just call the task. Result to force the task to run until the result is obtained.

Distribution cache and session (session) state

It is common for developers to build a Web application on a single development machine, and it is assumed that the product is running on a single server, but this is often not the case for the public-facing web. They are often deployed to a number of servers called Load balancer. Although you can still use In-proc ( knowledge points about In-proc and out-proc to supplement mode and sticky (sticky) session to deploy a Web application to multiple servers (the load balancer directs all requests belonging to the same session to a single server), you may have to preserve multiple copies of session data and cached data. For example, if you deploy a product to a Web farm that consists of 4 servers, and you keep the session data as In-proc, then a request arrives at a One-fourth or 25% opportunity that already contains the cached data, but if you use the centralized caching mechanism in the right place, Then the chance to find the cache entry for each request is 100%. This is critical for Web applications that rely heavily on cached data.

Another benefit of using a centralized caching mechanism (like app fabric or Redis) is the ability to proactively cache the system for the actual product. The proactive caching mechanism can be used to pre-load the most popular entries into the cache before the client requests an entry. This can help you dramatically improve the performance of your big data-driven applications if you use actual data sources to manage cache synchronization.

Create Web Gardens

As mentioned earlier, in an IO-constrained web app that contains a lot of long-running operations, such as a call to a Web service, you might want to release the main thread as much as possible. By default, each Web app runs under a main thread, and the main thread is responsible for keeping the Web site alive (alive), but unfortunately, when it's too busy, your site becomes unresponsive. Adding more "main threads" to your app is a way to do this by adding more worker processes to the Web site under IIS. Each worker process includes a separate main thread, so if one main thread is busy, there is another main thread to handle the incoming request.

Having multiple worker processes will turn your Web site into a Web garden, which requires you to persist session and application data to Out-proc (for example, a state Server or SQL Server).

Cleverly using caching and lazy loading

It is not necessary to stress that if you cache a bit of data that is frequently accessed into memory, this reduces the calls to the database and Web services. As previously mentioned, this is especially helpful for applications with limited IO, which can be unfortunate when the site is under low load.

Another way to improve site responsiveness is to use lazy loading. Lazy loading means there is no definite piece of data in the application, but it knows where the data is. For example, if you have a drop-down list on a Web page, it means that you want to display a list of products, and once the page is loaded, you do not have to load all the products from the database. You can add a jquery function to the page that fills the drop-down list the first time you drop it. You can also use the same techniques in many places in your code, such as when using LINQ queries and CLR collections.

Do not put C # code in the MVC view

The ASP. NET MVC view is compiled at run time, not at compile time, so if you include too much C # code in the view, your code will not compile and drop into the DLL file. Not only does this harm the testability of the software, it also makes the web app slower, because each page takes longer to get displayed (because they have to be compiled). Other flaws in adding code to the view are that they can't run asynchronously, so if you decide to build an app based on tap, you won't be able to take full advantage of the async methods and actions in the view.

For example, if you have a method in your code:

Public   async task<string> GetName(int code){varresult = ...return awaitResult;}

This method can run asynchronously in the context of an asynchronous ASP. NET MVC action, for example:

public  task<actionresult> index  ( CancellationToken CTX )  {var  Name = await  GetName (100 );} 

However, if this method is called in a view, because the view is not asynchronous, it must be run in a thread-blocking (thread-blocking) manner, such as:

var name = GetName(100).Result;

.ResultBlocks the running thread until the GetName() processing completes the request, so that the execution of the app stops for a while, but the thread is not blocked when the code is called with the await keyword.

Use fire & Forget when appropriate

Note: Fire & forget, literally fired, and then forgot to ignore it. The network explanation is to ignore after shooting.
If two or more operations do not generate a single transaction, you will most likely not have to run them sequentially. For example, if a user creates an account when registering with your site, once they register, you save their details to the database and send them an email, and you don't have to wait for the message to be sent to end the operation.

In this case, the best way is probably to open a new thread, let it send the message to the user, and then return to the main thread. This is called fire& forget, which can improve the responsiveness of applications.

Create for x64 CPU

32-bit's applications are limited to lower memory capacity and can access less CPU functions/instructions. To overcome these limitations, if your server is 64-bit, make sure your app is running in 64-bit mode (by ensuring that the option to run the Web site in IIS 32-bit mode is turned on). Then compile and generate code for the x64 CPU instead of any CPU.

An example of x64 useful is improving the responsiveness and performance of data-driven applications, and having a good caching mechanism is a must. In-proc is a memory boundary that consumes memory because everything is stored in the site's application pool. For the x86 process, the amount of memory that can be allocated is limited to 4GB, so that if loaded into the cache, the limit is quickly broken. If the same site is explicitly generated for the x64 CPU, then the memory limit is not considered, so that more entries can be added to the cache and then less communication with the database, which results in better performance.

Using the monitoring and diagnostic tools on the server

There may be more performance problems that you cannot see with the naked eye because they do not appear in the error log. When an application has been deployed to a server that has no chance to debug at all, identifying performance issues is a much scarier thing.

To find out about slow processing, thread blocking, hanging, errors, and so on, it is highly recommended that you install a monitoring and diagnostic tool on the server so that they keep track of and monitor your application. I personally use the newrelic to check the health of my online website. Get more information and create a free account look here !

Analysis of applications in operation

Once the site development is complete, deploy to IIS, then attach a parser (such as visual Studio Profiler), and then grab a snapshot of the multiple parts of the app. Like grabbing a snapshot of a purchase or user registration, and then checking to see if there is any code that causes slowness or blocking. Finding those hotspots in the early stages may save you a lot of time, honor and money.

Translated from:https://aspguy.wordpress.com/2014/02/17/building-high-performance-asp-net-applications/.
Thank the original author Aspguy

Extension:how ASP. NET Web application tests performance and load tests

Some suggestions for building high-performance ASP. NET application for senior developers

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.