Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build High performance ASP.NET

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "how to build a high-performance ASP.NET", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to build a high-performance ASP.NET.

The application should be load tested in the early stage

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

Using high-performance class libraries

Recently, when I was diagnosing performance problems with web sites, I found a hot issue in my code: JSON information from third-party web services must be deserialized multiple times. That Json information was deserialized by Newtonsoft.Json and proved that Newtonsoft.Json was not the fastest class library when deserializing, and then we replaced Json.Net with a faster class library (such as ServiceStack) and got better results.

If we had completed the load test in the early stages of selecting Json.Net as the serialization class library, we would have found the performance problem earlier, and we wouldn't have to make so many changes in the code or retest it completely again.

Is your application CPU-intensive or IO-intensive?

When starting to implement web applications and design projects, one of the first things you need to consider is whether your applications are CPU-intensive or IO-intensive? This is important for understanding strategies for extending applications.

For example, if your application is CPU-intensive, you may want to use synchronous mode, parallel processing, and so on. However, for a product that has many IO-constrained operations (such as communicating with external web services or network resources such as databases), an Task-based asynchronous mode may be more helpful for scaling out. In addition, in order to be able to create Web Gardens and Web Farms at some point in the future, you may want to have a centralized caching system that implements a load across multiple worker processes or services.

Use an asynchronous model based on Task, but be careful

If your product relies on many IO-restricted operations, or includes long-running operations that may consume valuable IIS threads to wait for an operation to complete, you'd better consider using Task-based asynchronous mode for ASP.NET MVC projects.

There are many manuals about asynchronous ASP.NET MVC actions on the Internet (such as this one), so this blog tries to avoid introducing knowledge about asynchronism. 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 processing completes. This means that if the web application is waiting for a response from an external resource, such as a web service, then the thread will be busy. The number of threads that can be used to process requests in the .net thread pool is also limited, so it is important to release threads as quickly as possible. An Task-based asynchronous action or method releases the thread after the request has been processed, then fetches a new thread from the thread pool, and uses the new thread to return the result of the action. In this way, multiple requests can be processed by multiple threads, which will bring better response to your application.

Although the TAP pattern is convenient for appropriate applications, it must be used with caution. When you use TAP to design or implement a project, you must pay attention to a few points (you can click here to see). However, the biggest challenge for developers using the async and await keywords is to know that they have to handle threads slightly differently in this context. For example, you can create a method that returns Task (such as Task "Product", the blog park's markdown does not support single angle brackets). Usually you can call the Run () method on that Task or just call task.Result to force the task to run until you get the result.

Distribution cache and session (session) status

It is common for developers to build a web application on a single development machine and assume that the product runs on a single server, but this is not usually the case for mass-oriented web. They are often deployed to multiple servers after being called load balancing. Although you can still deploy a web application to multiple servers (load balancer directs all requests belonging to the same session to a single server) using In-Proc (knowledge points about In-Proc and Out-Proc) and sticky Session, you may have to keep multiple copies of session data and cached data. For example, if you deploy the product to a web farm of four servers and you keep the session data as In-Proc, there is a 1/4 or 25% chance that a request will arrive at a request that already contains cached data, but if you use a centralized caching mechanism in the right place, the chance of finding a 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 (such as App Fabric or Redis) is the ability to implement an active caching system for actual products. The active caching mechanism can be used to preload the most popular entries into the cache before the client requests an entry. If you use actual data sources to manage cache synchronization, this will help you greatly improve the performance of big data-driven applications.

Create Web Gardens

As mentioned earlier, in an IO-constrained web application that contains many long-running operations (such as calls to web services), you may want to release the main thread as much as possible. By default, each web application runs under a main thread that is responsible for keeping the web site alive (alive), but unfortunately, when it is too busy, your site becomes unresponsive. Adding more "main threads" to the application is one 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 incoming requests.

Having multiple worker processes turns your web site into a Web Garden, which requires you to persist Session and application data into Out-Proc (such as a state server or Sql Server).

Ingenious use of caching and lazy loading

Needless to say, if you cache frequently accessed points of data in memory, this will reduce calls to databases and web services. As mentioned earlier, this is particularly helpful for IO-restricted applications, which can cause misfortune when the site is under low load.

Another way to improve site response is to use lazy loading. Lazy loading means that there will be no definite data slices in the application, but it knows where the data is. For example, if there is a drop-down list on the web page, this means that a list of products is displayed, and once the page is loaded, you don't have to load all the products from the database. You can add a jQuery function to the page that populates the drop-down list the first time you drop down. You can also use the same technique in many places in your code, such as when using Linq queries and CLR collections.

Do not put the 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 be compiled and put into the dll file. Not only does this harm the testability of the software, it also makes web applications slower because each page takes longer to display (because they have to be compiled). The other drawback of adding code to the view is that it cannot run asynchronously, so if you decide to build an application based on TAP, you will not be able to take full advantage of the asynchronous methods and action in the view.

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

Public async Task GetName (int code) {var result = … Return await result;}

This method can be run asynchronously in the context of an asynchronous ASP.NET MVC action, such as:

Public Task Index (CancellationToken ctx) {var name = await GetName;}

But if you call this method in a view, because the view is not asynchronous, it must be run in a way of thread thread-blocking, such as:

Var name = GetName. Result

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

Use Fire & Forget when appropriate

Note: Fire & Forget literally means launch, then forget it and ignore it. The network is interpreted as ignoring after shooting.

If two or more operations do not generate a single transaction, you probably don't have to run them sequentially. For example, if a user creates an account when registering on your site, once they sign up, you save their details to the database and send them an email. You don't have to wait for the email to be sent to end the operation.

In this case, the best way is probably to start a new thread, have it send mail to the user, and then return to the main thread. This is called Fire& Forget, and it can improve the responsiveness of the application.

Create for x64 CPU

The application of 32-bit is limited to a lower amount of memory and access to fewer CPU functions / instructions. To overcome these limitations, if your server is 64-bit, make sure your application is running in 64-bit mode (by making sure that the option to run the site in IIS's 32-bit mode is turned on). Then compile and generate the code for x64 CPU instead of Any CPU.

A useful example of x64 is to improve the responsiveness and performance of data-driven applications. A good caching mechanism is necessary. In-proc is memory-consuming because everything is stored at the memory boundary of the site's application pool. For x86 processes, the amount of memory that can be allocated is limited to 4GB, so that if loaded into the cache, this limit is quickly broken. If the same site is explicitly generated for x64 CPU, memory limitations need not be taken into account, so that more entries can be added to the cache and less communication with the database, which leads to better performance.

Use the monitoring and diagnostic tools on the server

There may be more performance problems that you can't see with the naked eye, because they don't appear in the error log. It is even more frightening to identify performance problems when the application has been deployed to a server that has little chance to debug.

To find slow processing, thread blocking, dangling, errors, etc., it is strongly recommended to install a monitoring and diagnostic tool on the server to continuously track and monitor your application. I personally use NewRelic to check the health of my online website. Get more information and create a free account. Look here!

Analyze the application in operation

Once the website development is complete, deploy to IIS, then attach an analyzer (such as Visual Studio Profiler), and then take snapshots of multiple parts of the application. For example, take a snapshot of an operation such as a purchase or user registration, and then check the disease to see if there is any code that is slow or blocked. Finding those hot spots at an early stage may save you a lot of time, honor and money.

At this point, I believe you have a deeper understanding of "how to build a high-performance ASP.NET". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report