C # asynchronous programming)

Source: Internet
Author: User

Differences between synchronous methods and asynchronous Methods
The synchronous method call needs to wait until the synchronous method execution is complete before the program continues to execute and return the result.
The Asynchronous Method returns immediately after being called so that the program can perform other operations while the called method completes its tasks.

Asynchronous programming Overview
. NET framework allows you to call any method asynchronously. Define the delegate with the same signature as the method to be called. The Common Language Runtime automatically defines the delegate with the appropriate Signature

The begininvoke and endinvoke methods.

The begininvoke method is used to start asynchronous calls. It has the same parameters as the method to be asynchronously executed, but there are two additional parameters (which will be described later ).

Begininvoke returns immediately without waiting for the asynchronous call to complete.
Begininvoke returns iasyncresult, which can be used to monitor the call progress.

The endinvoke method is used to retrieve asynchronous call results. After begininvoke is called, you can call the endinvoke method at any time. If the asynchronous call is not completed, endinvoke will be blocked

Asynchronous call is completed. Endinvoke parameters include the out and ref parameters of the method to be asynchronously executed (<out> byref and byref in Visual Basic) and

Iasyncresult returned by begininvoke.

Four common methods for asynchronous calling using begininvoke and endinvoke. After begininvoke is called, you can:

1. Perform some operations and call endinvoke until the call is completed.
2. Use iasyncresult. asyncwaithandle to get waithandle. Use its waitone method to block the execution until the waithandle signal is sent, and then call

Endinvoke. Here, the main program waits for the Asynchronous Method and the result of the Asynchronous Method.
3. Poll iasyncresult and iasyncresult. iscompeted returned by begininvoke to determine when the asynchronous call is completed and then call endinvoke. This processing is personally considered
Same.
4. Pass the delegate used for the callback method to begininvoke. This method is executed on the threadpool thread after the asynchronous call is completed. It can call endinvoke. This is mandatory.

In the callback function, convert iasyncresult. asyncstate (the last parameter of the begininvoke method) to delegate, and then use the delegate to execute endinvoke.
Warning endinvoke is always called after the asynchronous call is complete.

If you do not understand the above, you can understand it later.

Example
1) First, let's look at a simple Asynchronous Method without callback functions.

It is helpful to read the notes carefully when running the program. Also, if you synchronize the two methods in the annotation, you will find the speed advantage of asynchronous operation.

Using system;

Namespace consoleapplication1
{
Class class1
{
// Declare the delegate
Public Delegate void asynceventhandler ();

// Asynchronous Method
Void event1 ()
{
Console. writeline ("event1 start ");
System. Threading. thread. Sleep (4000 );
Console. writeline ("event1 end ");
}

// Synchronization Method
Void event2 ()
{
Console. writeline ("event2 start ");
Int I = 1;
While (I <1000)
{
I = I + 1;
Console. writeline ("event2" + I. tostring ());
}
Console. writeline ("event2 end ");
}

[Stathread]
Static void main (string [] ARGs)
{
Long start = 0;
Long end = 0;
Class1 c = new class1 ();
Console. writeline ("ready ");
Start = datetime. Now. ticks;

// Instance delegate
Asynceventhandler asy = new asynceventhandler (C. event1 );
// When the asynchronous call starts, no callback function or asyncstate are available, both of which are null.
Iasyncresult IA = asy. begininvoke (null, null );
// Start synchronization,
C. event2 ();
// Asynchronous end. If the end is not completed, the call is blocked until the call is complete. Return the return value of the function. If the return value exists.


Asy. endinvoke (IA );

// Synchronization.
// C. event1 ();
// C. event2 ();

End = datetime. Now. ticks;
Console. writeline ("time scale difference =" + convert. tostring (end-Start ));
Console. Readline ();
}
}
}

2) The following describes asynchronous webrequest and webresponse operations with callback functions.

Using system;
Using system. net;
Using system. Threading;
Using system. text;
Using system. IO;

// The requeststate class is used to pass
// Transmits data through asynchronous calls
Public class requeststate
{
Const int buffer_size = 1024;
Public stringbuilder requestdata;
Public byte [] bufferread;
Public httpwebrequest request;
Public stream responsestream;
// Create a decoder of the appropriate encoding type
Public decoder streamdecode = encoding. utf8.getdecoder ();

Public requeststate ()
{
Bufferread = new byte [buffer_size];
Requestdata = new stringbuilder ("");
Request = NULL;
Responsestream = NULL;
}
}

// Clientgetasync sends an asynchronous request
Class clientgetasync
{
Public static manualresetevent alldone = new manualresetevent (false );
Const int buffer_size = 1024;

Public static void main (string [] ARGs)
{

If (ARGs. Length <1)
{
Showusage ();
Return;
}

// Obtain the URI from the command line
Uri httpsite = new Uri (ARGs [0]);

// Create a request object
Httpwebrequest wreq = (httpwebrequest) webrequest. Create (httpsite );

// Create a status object
Requeststate rs = new requeststate ();

// Add the request to the status so that it can be passed back and forth
Rs. Request = wreq;

// Send an asynchronous request
Iasyncresult r = (iasyncresult) wreq. begingetresponse (New asynccallback (respcallback), RS );

// Set manualresetevent to wait,
// So that the application does not exit before calling the callback
Alldone. waitone ();
}

Public static void showusage ()
{
Console. writeline ("try to get (get) a URL ");
Console. writeline ("\ r \ n usage ::");
Console. writeline ("clientgetasync URL ");
Console. writeline ("Example ::");
Console. writeline ("clientgetasync http://www.microsoft.com/net ");
}

Private Static void respcallback (iasyncresult AR)
{
// Obtain the requeststate object from the asynchronous result
Requeststate rs = (requeststate) Ar. asyncstate;

// Obtain httpwebrequest from requeststate
Httpwebrequest Req = Rs. request;

// Call endgetresponse to generate the httpwebresponse object
// The object comes from the above request
Httpwebresponse resp = (httpwebresponse) Req. endgetresponse (AR );

// Since we have a response, we should
// The response stream starts to read data.
Stream responsestream = resp. getresponsestream ();

// This read operation is also completed asynchronously, so we
// The stream will be stored in requeststate
Rs. responsestream = responsestream;

// Note that Rs. bufferread is passed into beginread.
// This is the location where data will be read.
Iasyncresult iarread = responsestream. beginread (Rs. bufferread, 0, buffer_size, new asynccallback (readcallback), RS );
}

Private Static void readcallback (iasyncresult asyncresult)
{
// Obtain the requeststate object from asyncresult
Requeststate rs = (requeststate) asyncresult. asyncstate;

// Retrieve the responsestream set in respcallback
Stream responsestream = Rs. responsestream;

// At this time, Rs. bufferread should contain some data.
// The read operation will tell us if there is data
Int READ = responsestream. endread (asyncresult );

If (read> 0)
{
// Prepare the char array buffer for Unicode conversion.
Char [] charbuffer = new char [buffer_size];

// Convert byte streams to Char arrays and convert them to strings
// How many characters are displayed by Len to be converted to Unicode
Int Len = Rs. streamdecode. getchars (Rs. bufferread, 0, read, charbuffer, 0 );
String STR = new string (charbuffer, 0, Len );

// Append the recently read data to the requestdata stringbuilder object,
// This object is included in requeststate
Rs. requestdata. append (STR );

// Now send another asynchronous call to read more data
// Please note that this process will be called continuously
// Responsestream. endread returns-1
Iasyncresult AR = responsestream. beginread (Rs. bufferread, 0, buffer_size, new asynccallback (readcallback), RS );
}
Else
{
If (Rs. requestdata. length> 1)
{
// All data has been read, so it is displayed on the console
String strcontent;
Strcontent = Rs. requestdata. tostring ();
Console. writeline (strcontent );
}

// Close the response stream
Responsestream. Close ();

// Set manualresetevent so that the main thread can exit
Alldone. Set ();
}
Return;
}
}

Here there is a callback function, and there are asynchronous operations in the asynchronous callback.

First, the responsestream is obtained asynchronously and then the data is read asynchronously.

This program is very classic. You can learn a lot from this. Let's discuss it together.

Summary
As mentioned above,. NET Framework can call any method asynchronously. So Asynchronous is widely used.

There are also many asynchronous call methods in the. NET Framework class library. Generally, a pair of asynchronous delegate methods is formed at the beginning and end of "begin", and two callback functions and asyncstate parameters are added to form a macro embodiment of asynchronous operations. Therefore, to implement asynchronous programming, do not forget to delegate, begin, end, asynccallback delegation, and asyncstate instances (in the callback function, use iasyncresult. asyncstate for forced conversion), iasycresult (asynchronous monitoring), is enough to understand the true meaning of asynchronous.

# C # column

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.