[. NET multithreading] Asynchronous programming patterns

Source: Internet
Author: User
Tags apm

Starting with. NET 4.5, there are three asynchronous programming modes supported:

    • Event-based Asynchronous Programming design pattern (eap,event-based Asynchronous Pattern)
    • Asynchronous programming models (Apm,asynchronous programming model)
    • Task-based programming model (tap,task-based asynchronous Pattern)

A task-based Asynchronous Pattern (TAP) is a System.Threading.Tasks namespace-based task and TASK<TRESULT>, which is used to represent any asynchronous operation. TAP is the newly developed proposed asynchronous design pattern, which is discussed later.

Let's summarize the old 2 modes: EAP, APM.

See the similarities and differences between the 2 types of asynchronous programming in the following ways:

    • Naming, parameters, return values
    • Typical applications
    • Catching exceptions
    • State
    • Cancel operation
    • Progress report
EAP naming, parameters, return values

The code naming of the EAP programming pattern has the following characteristics:

    • There will be one or more methods named [Method name]async. These methods may create a synchronous version of the Mirror, which performs the same action on the current thread.
    • The class may also have a "[Method name]completed" event that listens for the results of an asynchronous method.)
    • It may have a "[Method name]asynccancel" (or just CancelAsync) method that cancels an asynchronous operation in progress.

Parameters and return values are not specified, depending on business requirements

Typical applications

To request a URL as an example

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 ())            {                //Get completed                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"; Gets the returned result log + = "|result_size=" + Utility.getstrlen (e.result); Utility.Log (LOG); } }

Catching exceptions

Exception information is typically passed in the event arguments of the completed. Immediately following the example above, if you need to get the returned exception information, you need to rewrite the downloadstringcomleted method.

static void Webclient_downloadstringcompleted (object sender, DownloadStringCompletedEventArgs e)        {            string Log = "asyncrun:download_completed";            if (e.error! = null)    //visible, the parameter in the event transmits exception information        {                //An exception is logged,           log + = "|error=" + e.error.message;            }            else            {                //No exception appears, log result           log + = "|result_size=" + Utility.getstrlen (E.result);            }            Utility.Log (LOG);        }
State

EAP itself does not maintain state and, if necessary, should set different time responses to different state changes;

Assuming just downloadstringasync, you need to add several more state values, you can consider adding several more events.

Such as

Event downloadstringstarted (response download just started)

Event downloadstringpending (in response to download blocking)

Event Downloadstringcancel (when responding to a download cancellation)

Wait a minute.

Cancel operation

By naming the specification, if the operation has a "[Method name]asynccancel" (or just CancelAsync) method, the cancel operation is supported.

The state capture of the cancellation, or whether to export HTML as an example of the download URL, or whether the downloadstringcompleted gets canceled or not. DownloadStringCompletedEventArgs. Cancelled

Note that if the user executes the CancelAsync, the In the downloadstringcompletedeventargs.error will get to the corresponding exception, at this time do not take downloadstringcompletedeventargs.result.

Progress report

EAP has no hard-to-say support for progress reports, but it can be a natural way to respond to changes in time.

In the current example, WebClient provides a response event that downloadprogresschanged makes progress changes.

APM naming, parameters, return values

The code naming of APM's programming model has the following characteristics:

    • Asynchronous operations that use the IAsyncResult design pattern are implemented by two methods named [begin operation name] and [end action name], which begin and end the asynchronous operation 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 the [begin operation name] is called, the application can continue executing the instruction on the calling thread while the asynchronous operation executes on the other thread. Each time the [begin operation name] is called, the application should also invoke [end action name] to get the result of the operation.
Typical applications

To request a URL as an example

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 () {Utilit            Y.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 invocation of a delegate also uses the APM pattern, which is powerful in that it enables any method to programmatically invoke asynchronously.

         <summary>///A time-consuming method///</summary> private static void Caluatemanynumber () {                for (int i = 0; i < i++) {thread.sleep (100);            Console.WriteLine ("Loop==>" +i.tostring ()); }}///<summary>//delegate, allowing time-consuming methods to execute asynchronously//</summary> public static void Asyn            Cdelegate () {//delegate simply wrap up the 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"); }
Catching exceptions

The exception information is obtained in [end operation name].

        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 mode itself does not support status diversification and cancellation operations, progress reporting.

[. NET multithreading] Asynchronous programming patterns

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.