C # Asynchronous Programming Learning (I.)

Source: Internet
Author: User
Tags apm

Asynchronous programming can avoid thread occupancy while waiting for a task to complete, but it is still a headache for you to implement programming correctly.

. NET Framework, there are three different models to simplify asynchronous programming.

. NET 1. The Beginfoo/endfoo method in X, using IAsyncResult and AsyncCallback to propagate the results.

. NET 2. The event-based Asynchronous Pattern in 0, implemented using BackgroundWorker and WebClient.

. NET 4 is introduced with the. NET 4. 5 Extended Task Parallel Library (TPL).

(i) APM (asynchronous Programming Model) C # version 1.1

The most representative feature of the APM asynchronous programming model is that an asynchronous function consists of two methods beginning with begin and end. The method at the beginning of begin represents the execution of the initiating asynchronous function, and the method at the beginning of the end indicates waiting for the asynchronous function to execute and return the execution result;

Simulation implementation:

 Public classWorker { Public intAGet;Set; }  Public intBGet;Set; } Private intRGet;Set; }        ManualResetEvent et;  Public voidBeginwork (Action action) {et=NewManualResetEvent (false); NewThread (() ={R= A +B; Thread.Sleep ( +); Et.                Set (); if(NULL!=action)                {action (); }            }).        Start (); }         Public intendwork () {if(NULL==ET) {                Throw NewException ("before calling Endwork, you need to call Beginwork first"); }            Else{et.                WaitOne (); returnR; }        }     }
View Code

Calling code:

Static void Main (string[] args)        {           new  Worker ();            W.beginwork (()= {                Console.WriteLine ("Thread id:{0},count:{1}"  , Thread.CurrentThread.ManagedThreadId,                    w.endwork ());            });            Console.WriteLine ("Thread id:{0}", THREAD.CURRENTTHREAD.MANAGEDTHREADID);            Console.ReadLine ();        }
View Code

How the standard APM model implements asynchronous programming:

IAsyncResult interface

The IAsyncResult interface defines the state of the asynchronous function, and the specific properties and meanings of the interface are as follows:

 //represents the state of an asynchronous operation. [ComVisible (true)]     Public InterfaceIAsyncResult {//        //Summary://gets a value that indicates whether the asynchronous operation has completed. //        //return Result://true if the operation has completed, otherwise false.         BOOLiscompleted {Get; } //        //Summary://gets the System.Threading.WaitHandle that is used to wait for the asynchronous operation to complete. //        //return Result://the System.Threading.WaitHandle to wait for the asynchronous operation to complete. WaitHandle AsyncWaitHandle {Get; } //        //Summary://gets a user-defined object that qualifies or contains information about the asynchronous operation. //        //return Result://a user-defined object that qualifies or contains information about the asynchronous operation.         Objectasyncstate {Get; } //        //Summary://gets a value that indicates whether the asynchronous operation is complete synchronously. //        //return Result://true if the asynchronous operation completes synchronously; otherwise false.         BOOLcompletedsynchronously {Get; } }
View Code

Implementation of the interface:

 Public classNewworker { Public classWorkerasyncresult:iasyncresult {AsyncCallback callback;  PublicWorkerasyncresult (intAintB, AsyncCallback callback,Objectasyncstate) {A=A; B=b; State=asyncstate;  This. Callback =callback; NewThread (Count). Start ( This); }             Public intAGet;Set; }  Public intBGet;Set; }  Public intRGet;Private Set; } Private ObjectState ;  Public Objectasyncstate {Get                {                    returnState ; }            }            PrivateManualResetEvent WaitHandle;  PublicWaitHandle AsyncWaitHandle {Get                {                    if(NULL==waitHandle) {WaitHandle=NewManualResetEvent (false); }                    returnWaitHandle; }            }            Private BOOLcompletedsynchronously;  Public BOOLcompletedsynchronously {Get                {                    returncompletedsynchronously; }            }            Private BOOLiscompleted;  Public BOOLiscompleted {Get                {                    returniscompleted; }            }            Private Static voidCount (ObjectState ) {                varresult = State asWorkerasyncresult; Result. R= result. A +result.                B Thread.Sleep ( +); result.completedsynchronously=false; Result.iscompleted=true; ((ManualResetEvent) result. AsyncWaitHandle).                Set (); if(Result.callback! =NULL) {result.callback (result); }            }        }         Public intNUM1 {Get;Set; }  Public intNum2 {Get;Set; }  PublicIAsyncResult Beginwork (AsyncCallback usercallback,Objectasyncstate) {IAsyncResult result=NewWorkerasyncresult (Num1,num2,usercallback, asyncstate); returnresult; }         Public intendwork (IAsyncResult result) {Workerasyncresult R= Result asWorkerasyncresult;            R.asyncwaithandle.waitone (); returnR.R; }    }
View Code

Call:

Static voidMain (string[] args) {Newworker W2=NewNewworker (); W2. Num1=Ten; W2. Num2= A; IAsyncResult R=NULL; R= W2. Beginwork ((obj) ={Console.WriteLine ("Thread Id:{0},count:{1}", Thread.CurrentThread.ManagedThreadId, W2.            Endwork (R)); }, NULL); Console.WriteLine ("Thread id:{0}", Thread.CurrentThread.ManagedThreadId);        Console.ReadLine (); }
View Code

Delegate asynchronous programming (APM standard implementation)

 Public classNewWorker2 {Func<int,int,int>Action;  PublicNewWorker2 () {action=Newfunc<int,int,int>(work); }         PublicIAsyncResult Beginwork (AsyncCallback callback,ObjectState ) {            Dynamicobj =State ; returnAction. BeginInvoke (obj. A, obj. B, Callback, This); }         Public intendwork (IAsyncResult asyncResult) {Try            {                returnaction.            EndInvoke (AsyncResult); }            Catch(Exception ex) {Throwex; }        }        Private intWork (intAintb) {Thread.Sleep ( +); returnA +b; }    }
View Code
 Static voidMain (string[] args) {NewWorker2 W2=NewNewWorker2 (); IAsyncResult R=NULL; R= W2. Beginwork ((obj) ={Console.WriteLine ("Thread Id:{0},count:{1}", Thread.CurrentThread.ManagedThreadId, W2.            Endwork (R)); }, New{A =Ten, B = One }); Console.WriteLine ("Thread id:{0}", Thread.CurrentThread.ManagedThreadId);        Console.ReadLine (); }
View Code

Learning sites: 77917172

C # Asynchronous Programming Learning (I.)

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.