starting with. NET 4.5, three asynchronous programming modes supported:
• event-based Asynchronous Programming Design Model (eap,event-based Asynchronous Pattern)
• Asynchronous programming models (Apm,asynchronous programming model)
• Task-based programming Model (tap,task-based Asynchronous Pattern)
The task-based Asynchronous Pattern (TAP) is a task and task<tresult> based on the System.Threading.Tasks namespace, and is used to represent arbitrary asynchronous operations. TAP is a newly developed, proposed asynchronous design pattern, which is discussed later.
Let's summarize the old 2 modes: EAP, APM。
From the following aspects, see the similarities and differences of these 2 kinds of asynchronous programming methods:
• Name, parameter, return value
• Typical applications
• Catch Exceptions
• Status
• Cancel Operation
• Progress report
EAP
name, parameter, return value
The code naming for the EAP programming model has the following characteristics:
• There will be one or more methods named [Method name]async]. These methods may create a mirrored version of the synchronization that performs the same action on the current thread.
• The class may also have a [method name]completed] event that listens for the results of the asynchronous method.
• It may have a "[Method name]asynccancel" (or just CancelAsync) method that cancels an asynchronous operation in progress.
No special rules for parameters and return values, determined by business requirements
Typical Applications
To request a URL as an example
Copy Code code as follows:
public class Eap_typical
{
public static void Asyncrun ()
{
Utility.Log ("Asyncrun:start");
Test URLs
string url = http://sports.163.com/nba/;
using (WebClient WebClient = new WebClient ())
{
Get the complete situation
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";
Get return result
Log = + "|result_size=" + Utility.getstrlen (E.result);
Utility.Log (LOG);
}
}
Catch Exception
Exception information is generally passed in completed event arguments. Immediately following the example above, if you need to get the exception information returned, you need to rewrite the downloadstringcomleted method.
Copy Code code as follows:
static void Webclient_downloadstringcompleted (object sender, DownloadStringCompletedEventArgs e)
{
String log = "asyncrun:download_completed";
if (e.error!= null)//visible, the parameter of the event transmits exception information
{
An exception is logged, and an exception is recorded
Log = + "|error=" + e.error.message;
}
Else
{
If no exception occurs, the result is logged
Log = + "|result_size=" + Utility.getstrlen (E.result);
}
Utility.Log (LOG);
}
State
EAP itself does not maintain the state, if necessary, should set different time to respond to different state changes;
Assuming that the downloadstringasync, you need to add a few more state values, you can consider adding a few more events.
Such as
Event downloadstringstarted (response download just started)
Event downloadstringpending (in response to download blocking)
Event Downloadstringcancel (when response to download is canceled)
Wait a minute.
Cancel Operation
By the naming convention, a cancel operation is supported if the action has a [method name]asynccancel] (or just CancelAsync) method.
Cancel the state capture, or whether to export HTML for the download URL just now, or the status of Downloadstringcompleted to get canceled. DownloadStringCompletedEventArgs. Cancelled
Note that if the user executes the CancelAsync, In the downloadstringcompletedeventargs.error will get the corresponding exception, at this time do not take downloadstringcompletedeventargs.result.
Progress Report
EAP does not have the mandatory requirement to support progress reports, but it is possible to naturally respond to progress changes through time.
In the current example, WebClient provides downloadprogresschanged response events that make progress changes.
APM
name, parameter, return value
The code naming of APM's programming pattern has the following characteristics:
• Asynchronous operations using the IAsyncResult design pattern are implemented by means of two methods named [begin operation name] and [end operation name], which start and close the asynchronous operation name respectively. For example, the FileStream class provides BeginRead and EndRead methods to read bytes asynchronously from a file. These two methods implement the asynchronous version of the Read method.
• After invoking [begin operation name], the application can continue to execute instructions on the calling thread while the asynchronous operation executes on another thread. Each time the begin operation name is invoked, the application should also call [end operation name] to obtain the result of the operation.
Typical Applications
To request a URL as an example
Copy Code code 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 URLs
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 invocation of a delegate also uses the APM pattern, which is powerful in that it allows any method to programmatically invoke the asynchronous invocation.
Copy Code code as follows:
<summary>
A time-consuming approach
</summary>
private static void Caluatemanynumber () {
for (int i = 0; i < i++)
{
Thread.Sleep (100);
Console.WriteLine ("Loop==>" +i.tostring ());
}
}
<summary>
Delegates, allowing time-consuming methods to execute asynchronously
</summary>
public static void AsyncDelegate () {
Commissioned a simple package of methods
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");
}
Catch Exception
The exception information is to be obtained in the [end operation name].
Copy Code code 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 operations, progress reports
The APM model itself does not support state diversification and cancellation operations, progress reports.