Three asynchronous programming modes supported starting from. NET 4.5:
• Event-based Asynchronous Pattern)
• Asynchronous Programming Model (APM, Asynchronous Programming Model)
• Task-based Programming Model (TAP, Task-based Asynchronous Pattern)
The Task-based asynchronous mode (TAP) is a Task and a Task <TResult> Based on the System. Threading. Tasks namespace, used to represent any asynchronous operation. The Asynchronous Design Mode is recommended for the new development of TAP, which will be discussed later.
Summarize the two old modes: EAP and APM..
The similarities and differences between the two asynchronous programming methods are as follows:
• Name, parameter, and return value
• Typical applications
• Capture exceptions
• Status
• Cancel Operation
• Progress Report
EAP
Naming, parameters, and returned values
The code naming in the EAP programming mode has the following features:
• There will be one or more methods named "[method name] Async. These methods may create images of the synchronous version, which will perform the same operation on the current thread.
• This class may also have a "[method name] Completed" event to listen to the results of asynchronous methods.
• It may have a "[method name] AsyncCancel" (or just CancelAsync) method to cancel ongoing asynchronous operations.
There are no special rules for parameters and return values, depending on business needs
Typical applications
Take a request for a Url as an ExampleCopy codeThe Code is as follows: public class EAP_Typical
{
Public static void AsyncRun ()
{
Utility. Log ("AsyncRun: start ");
// Test URL
String url = http://sports.163.com/nba /;
Using (WebClient webClient = new WebClient ())
{
// Obtain completion Information
WebClient. DownloadStringCompleted + = new DownloadStringCompletedEventHandler (webClient_DownloadStringCompleted );
WebClient. DownloadStringAsync (new Uri (url ));
Utility. Log ("AsyncRun: download_start ");
}
}
Static void webClient_DownloadStringCompleted (object sender, DownloadStringCompletedEventArgs e)
{
String log = "AsyncRun: download_completed ";
// Obtain the returned results
Log + = "| result_size =" + Utility. GetStrLen (e. Result );
Utility. Log (log );
}
}
Capture exceptions
Exception information is generally transmitted in the Completed event parameters. In the preceding example, if you want to obtain the returned exception information, you must rewrite the DownloadStringComleted method.Copy codeThe Code is as follows: static void webClient_DownloadStringCompleted (object sender, DownloadStringCompletedEventArgs e)
{
String log = "AsyncRun: download_completed ";
If (e. Error! = Null) // visible, the event parameter transmission exception information
{
// If an exception occurs, an exception is recorded.
Log + = "| error =" + e. Error. Message;
}
Else
{
// If no exception occurs, the result is recorded.
Log + = "| result_size =" + Utility. GetStrLen (e. Result );
}
Utility. Log (log );
}
Status
EAP itself does not maintain the status. If necessary, you should set different times to respond to different state changes;
Suppose that the DownloadStringAsync just now requires several more State values. You can consider adding several more events.
For example
Event DownloadStringStarted (Response download started)
Event DownloadStringPending (Response download blocking)
Event DownloadStringCancel (response to download cancellation)
And so on.
Cancel operation
According to the naming conventions, if the operation pair should have the "[method name] AsyncCancel" (or only CancelAsync) method, the operation can be canceled.
The capture of canceled status is based on the html output from the downloaded Url just now, or whether the download is canceled at DownloadStringCompleted. DownloadStringCompletedEventArgs. Cancelled
Note that if the user executes CancelAsync, the corresponding exception is obtained after DownloadStringCompletedEventArgs. Error. In this case, do not obtain DownloadStringCompletedEventArgs. Result.
Progress Report
EAP does not require support for progress reports, but it can easily respond to progress changes through time.
In the current example, WebClient provides a response event for DownloadProgressChanged to make progress changes.
APM
Naming, parameters, and returned values
The code naming in APM programming mode has the following features:
• Asynchronous operations in the IAsyncResult design mode are implemented through two methods: [Begin operation name] and [End operation name, the two methods start and end the asynchronous operation respectively. For example, the FileStream class provides the BeginRead and EndRead methods to asynchronously read bytes from files. The two methods implement the asynchronous version of the Read method.
• After calling the [Begin operation name], the application can continue to execute commands on the calling thread, while asynchronous operations are executed on another thread. Each time you call the [Begin operation name], the application should also call the [End operation name] to obtain the operation result.
Typical applications
Take a request for a Url as an ExampleCopy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Net;
Using System. IO;
Namespace AsyncTest1.APM
{
Public class APMTestRun1
{
Public static void AsyncRun ()
{
Utility. Log ("APMAsyncRun: start ");
// Test URL
String url = "http://sports.163.com/nba ";
HttpWebRequest webRequest = HttpWebRequest. Create (url) as HttpWebRequest;
WebRequest. BeginGetResponse (Callback, webRequest );
Utility. Log ("AsyncRun: download_start ");
}
Private static void Callback (IAsyncResult ar)
{
Var source = ar. AsyncState as HttpWebRequest;
Var response = source. EndGetResponse (ar );
Using (var stream = response. GetResponseStream ())
{
Using (var reader = new StreamReader (stream ))
{
String content = reader. ReadToEnd ();
Utility. Log ("AsyncRun: result_size =" + Utility. GetStrLen (content ));
}
}
}
}
}
The asynchronous call of the delegate also uses the APM mode. The advantage of this method is that it can make any method program asynchronous call.Copy codeThe Code is as follows: // <summary>
/// A time-consuming Method
/// </Summary>
Private static void CaluateManyNumber (){
For (int I = 0; I <10; I ++)
{
Thread. Sleep (100 );
Console. WriteLine ("loop =>" + I. ToString ());
}
}
/// <Summary>
/// Delegate so that time-consuming methods can be executed asynchronously
/// </Summary>
Public static void AsyncDelegate (){
// Delegate a simple packaging method
Action action = CaluateManyNumber;
Action. BeginInvoke (DelegateCallback, null );
Console. WriteLine ("action begin ");
}
/// <Summary>
/// Asynchronous callback
/// </Summary>
/// <Param name = "ar"> </param>
Private static void DelegateCallback (IAsyncResult ar ){
AsyncResult asyncResult = ar as AsyncResult;
Var delegateSource = asyncResult. AsyncDelegate as Action;
DelegateSource. EndInvoke (ar );
Console. WriteLine ("action end ");
}
Capture exceptions
The exception information must be obtained in [End operation name.Copy codeThe Code is as follows: private static void Callback (IAsyncResult ar)
{
Var source = ar. AsyncState as HttpWebRequest;
WebResponse response = null;
Try
{
Response = source. EndGetResponse (ar );
}
Catch (Exception ex ){
Utility. Log ("error:" + ex. Message );
Response = null;
}
If (response! = Null)
{
Using (var stream = response. GetResponseStream ())
{
Using (var reader = new StreamReader (stream ))
{
String content = reader. ReadToEnd ();
Utility. Log ("AsyncRun: result_size =" + Utility. GetStrLen (content ));
}
}
}
}
Status and cancel operation and progress report
APM mode does not support status diversification, Operation cancellation, and progress report.