Asynchronous programming in ASP. NET

Source: Internet
Author: User
Tags website performance

 

Asynchronous programming in ASP. NET

Why use asynchronous programming in ASP. NET?

ASP. NET uses threads in the Common Language Runtime Library (CLR) thread pool to process requests. As long as there are available threads in the thread pool, ASP. NET will not have any trouble in scheduling incoming requests. However, once the thread pool is saturated (that is, all threads in the pool are busy processing requests, but no available threads), new requests must wait for the thread to be available. If the deadlock becomes serious and the queue reaches the capacity limit, ASP. NET will be helpless, and the web server will reject new requests and return the HTTP 503 status (the server is too busy ).

One solution is to increase the thread pool limit to create more threads. This is a method that developers often take when their customers report frequent "server unavailability" errors. Another common method is to discard faulty hardware and add more servers to the Web farm. However, increasing the number of threads or servers does not fundamentally solve this problem.

A truly scalable ASP. NET Website should make full use of the thread pool.If the thread pool is saturated because all threads consume CPU, you have almost no choice but to add servers. However, most Web ApplicationsProgramYou can call databases, web services, or other external entities, and restrict scalability by forcing the thread pool to wait for database queries, Web service calls, and other I/O operations. Data-driven web page query may take several thousandths of a secondCode, Takes a few seconds to wait for the database to query and return.When the query is incomplete, the thread allocated to the request cannot serve other requests. This is the so-called glass roof.If you want to build a highly scalable website, this situation must be avoided.Remember: When throughput is involved, unless handled properly
I/O will become a big problem.

Therefore, asynchronous programming should be used for Io operations to improve website throughput and scalability. At the same time, we should know that,Asynchronous Io programming cannot shorten the time for one Io operation.Therefore, it does not make users feel the speed of the website. However, if multiple Io operations are required for a page in sequence, asynchronous operations are performed on each Io,At this time, the page operation completion time will be the time that takes the longest time in multiple Io operations, rather than the sum of the time consumed by multiple Io operations.. At this time, the user will feel the website is getting faster.

 

How do I choose synchronous or asynchronous operations?

This is just a few guidelines; you must check each application one by one to determine whether asynchronous operation methods can help improve performance.

 

A synchronization operation is usually used when the following conditions are met:

1. The operation is very simple or the running time is very short.

2. Simplicity is more important than efficiency.

3. This operation mainly involves CPU operations rather than operations that contain a large amount of disk or network overhead. The Asynchronous Operation Method for CPU binding does not provide any benefit and more system overhead is caused by frequent inter-thread switching.

 

Generally, asynchronous operations are used when the following conditions are met:

1. The operation is network binding or I/O binding, not CPU binding.

2. the test shows that blocking operations are a bottleneck on website performance. IIS can provide services for more requests by using asynchronous operation methods for these blocking calls.

3. parallelism is more important than code simplicity.

4. You want to provide a mechanism that allows users to cancel long-running requests.

 

How to Use asynchronous programming in ASP. NET?

There are three asynchronous programming methods in ASP. NET:

I. asynchronous page

If you want to perform relatively long I/O operations on some pages, they should become asynchronous pages. It takes five seconds for a page to query the database (because it returns a large amount of data and locks the target to a remote database through a large number of loaded connections ), the five seconds that the thread assigns to the request cannot be used for other requests. If each request is processed based on this, the application will soon be paused.

When an asynchronous page is used,After a request arrives, ASP. NET assigns a thread to it. This request starts to be processed in this thread. When a database is selected, the request starts an asynchronous ADO. Net query and returns the thread to the thread pool. When the query is complete, ADO. Net calls back to ASP. NET, ASP. NET calls out another thread from the thread pool, and resumes processing requests.

To use an asynchronous page, follow these steps:

1. Set the async = "true" attribute in the ASPX page command.

2. Call the addonprerendercompleteasync or registerasynctask method in the page_load method to register the start and end processing programs.

3. Call the database query asynchronously (async = "true" needs to be set in the connection string), file operations (use the fileoptions. asynchronous attribute to open the file stream), or WebService.

 

The following is an example of an asynchronous page using the addonprerendercompleteasync method.

Using system; using system. data; using system. data. sqlclient; using system. web; using system. web. ui; using system. web. UI. webcontrols; using system. web. configuration; public partial class asyncdatabind: system. web. UI. page {private sqlconnection _ connection; private sqlcommand _ command; private sqldatareader _ reader; protected void page_load (Object sender, eventargs e) {If (! Ispostback) {events (new events (beginasyncoperation), new endeventhandler (endasyncoperation) ;}} iasyncresult events (Object sender, eventargs E, asynccallback CB, object state) {string connect = webconfigurationmanager. connectionstrings ["asyncpubs"]. connectionstring; _ connection = new sqlconnection (CONNECT); _ connection. open (); _ command = new sqlco MmAnd ("select title_id, title, price from titles", _ connection); // principle Description: The function that CB points to here is void onasynchandlercompletion (system. iasyncresult), // this function will be called after the inexecutereader asynchronous call is complete. In this function, the endeventhandler delegate registered in page_load // will be executed (here it is the endasyncoperation function) return _ command. beginexecutereader (CB, State);} void endasyncoperation (iasyncresult AR) {_ reader = _ command. endexecutereader (AR);} protected void page_prer Endercomplete (Object sender, eventargs e) {output. datasource = _ reader; output. databind ();} public override void dispose () {If (_ connection! = NULL) _ connection. Close (); base. Dispose ();}}

 

 

 

Ii. asynchronous HTTP processing program

By writing a custom HTTP processing program, you can extend ASP. NET to support other file types. But what's more interesting is that you can deploy HTTP handlers in the ashx file and use them as the targets of HTTP requests. This is the correct way to build a web endpoint that dynamically generates images or retrieves images from a database. You only need to include the tag (or image control) in the page and point it to the ashx that creates or retrieves the image.Locking a target to an ashx file with a request is more effective than locking the target to An ASPX file, because the ashx file has less overhead during processing.

During asynchronous HTTP processing, ASP. NET puts the threads normally used for external processes back into the thread pool until the handler receives a callback from an external process. Because only a limited number of threads can be executed at the same time, this can avoid blocking threads and improve performance. If many users are requesting synchronous HTTP processing programs that depend on external processes, the operating system may soon run out of all threads because a large number of threads are blocked and waiting for external processes.

 

The following is an example of an asynchronous HTTP processing program that uses asynchronous reading of image files.

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. io; namespace testweb {public class searchimageasync: ihttpasynchandler {private string imgpath = "images/bg.jpg"; private const int buffer_size = 1024; Public writable beginprocessrequest (httpcontext context, asynccallback CB, object extradata) {filestream FS = new filestream (context. server. mappath (im Gpath), filemode. open, fileaccess. read, fileshare. read, buffer_size, fileoptions. asynchronous); byte [] buffer = new byte [buffer_size]; memorystream result = new memorystream (); Return FS. beginread (buffer, 0, buffer_size, new asynccallback (readfilecb), new readfilestateinfo (context, CB, extradata, FS, buffer, result);} private void readfilecb (iasyncresult AR) {readfilestateinfo state = ar. asyncs Tate as readfilestateinfo; If (State = NULL) return; filestream FS = state. readfilestream; int COUNT = FS. endread (AR); If (count> 0) {state. resultstream. write (state. readbuffer, 0, count); FS. beginread (state. readbuffer, 0, buffer_size, new asynccallback (readfilecb), State);} else {If (FS! = NULL) {FS. close (); FS = NULL;} state. endprocesscb (AR) ;}} public void endprocessrequest (iasyncresult result) {readfilestateinfo state = result. asyncstate as readfilestateinfo; If (State = NULL) return; State. context. response. contenttype = "image/*"; State. context. response. binarywrite (state. resultstream. toarray (); State. resultstream. close () ;}public bool isreusable {get {return false ;}} public void processrequest (httpcontext context) {Throw new notimplementedexception () ;}} public class readfilestateinfo {private asynccallback mendprocesscb; public asynccallback endprocesscb {get {return this. mendprocesscb;} set {This. mendprocesscb = value ;}} private object masyncextradata; public object asyncextradata {get {return this. masyncextradata;} set {This. masyncextradata = value ;}} private filestream mreadfilestream; Public filestream readfilestream {get {return this. mreadfilestream;} set {This. mreadfilestream = value ;}} private byte [] mreadbuffer; /// <summary> /// read the buffer of the file /// </Summary> Public byte [] readbuffer {get {return this. mreadbuffer;} set {This. mreadbuffer = value ;}} private memorystream mresultstream; // <summary> // memory stream for storing results /// </Summary> Public memorystream resultstream {get {return this. mresultstream;} set {This. mresultstream = value ;}} private httpcontext mcontext; Public httpcontext context {get {return this. mcontext;} set {This. mcontext = value ;}} public readfilestateinfo (httpcontext context, asynccallback CB, object extradata, filestream readfilestream, byte [] readbuffer, memorystream result) {This. mcontext = context; this. mendprocesscb = CB; this. masyncextradata = extradata; this. mreadfilestream = readfilestream; this. mreadbuffer = readbuffer; this. mresultstream = Result ;}}}

 

Register the HTTP handler in vs2010 (Classic Mode of iis7.0)

 
<Configuration> <system. webserver>  

 

 

Now the image can be opened through the extension *. imgasync (the image is read only to illustrate the asynchronous operation method ).

 

Iii. asynchronous HTTP Module

The HTTP module is an object located in the ASP. NET pipeline. in the pipeline, it can view or even modify incoming requests and outgoing responses. Many major services in ASP. NET are implemented in the form of HTTP modules, including identity authentication, authorization, and output caching. By writing custom HTTP modules and inserting them into pipelines, you can expand ASP. NET. When you do this, you must carefully consider whether these HTTP modules should be asynchronous.

To use the asynchronous HTTP module, you can call application. addonprerequesthandlerexecuteasync to register two callback functions in the init method of ihttpmodule.

The following is an example of an httpmodule that records user access logs.

Using system; using system. web; using system. io; using system. threading; using system. text; namespace testweb {public class asyncrequestlogmodule: ihttpmodule {private filestream _ file; Private Static long _ Position = 0; Private Static object _ Lock = new object (); public void Init (httpapplication application) {application. addonprerequesthandlerexecuteasync (New begineventhandler (beginprerequesthandle Rexecute), new endeventhandler (endprerequesthandlerexecute);} iasyncresult convert (Object source, eventargs E, asynccallback CB, object state) {httpapplication APP = (httpapplication) source; datetime time = datetime. now; string line = string. format ("{: d} {: t} {2, 32} {3} \ r \ n", time, time, app. user. identity. isauthenticated? App. user. identity. name: app. request. userhostaddress, app. request. URL); byte [] Output = encoding. ASCII. getbytes (line); lock (_ Lock) {_ file = new filestream (httpcontext. current. server. mappath ("~ /App_data/requestlog.txt "), filemode. openorcreate, fileaccess. write, fileshare. writes, 1024, true); _ file. seek (_ Position, seekorigin. begin); _ Position + = output. length; return _ file. beginwrite (output, 0, output. length, CB, state) ;}} void endprerequesthandlerexecute (iasyncresult AR) {_ file. endwrite (AR); _ file. close () ;}public void dispose (){}}}

 

Register the httpmodule in the web. config file.

 
<Configuration> <system. web>  

 

Reference: http://msdn.microsoft.com/zh-cn/magazine/cc163463.aspx

Http://www.cnblogs.com/flier/archive/2005/12/27/305233.aspx

 

 

Related Article

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.