C # Multithreading and Asynchrony (iii)--some asynchronous programming patterns

Source: Internet
Author: User

One, the Task Parallel library

The Task Parellel Library is a class library in the BCL that greatly simplifies parallel programming, with Parallel.For and Parallel.ForEach as an example. It is common in C # to use For/foreach loops, and if iterations do not depend on the results of the last iteration, the parallel processing of the iterations on different processors will greatly improve the efficiency of the operation. Parallel.For and Parallel.ForEach are designed for this purpose.

A chestnut:

1      Static voidMain (string[] args)2         {3             //Parallel.For calculates the square of 0 to 104Parallel.For (1,6, i =5             {6Console.WriteLine ("The square of {0} is {1}", I, I *i);7             });8 9             //Parallel.ForEach Calculating the length of each stringTen             string[] STRs = {"We"," hold","these","Truths" }; OneParallel.ForEach (STRs, i = Console.WriteLine ("{0} has {1} letters", I,i.length)); A Console.readkey (); -}

Operation Result:

Second, timers (timer)

Timers provide a way to periodically repeat an asynchronous method , and when the timer expires, the system opens a callback method from a thread in the thread pool, takes state as an argument, and starts running.

The most common constructors for a timer are:

Timer (Timecallback callback,object State,uintUINT period)

Callback is a delegate with a return value of void, state is an argument passed in callback, Duetime is the time before the first call, and period is the interval of two calls

A chestnut:

1  class Program2     {3         intCount =0;4         voidRun (ObjectState )5         {6Console.WriteLine ("{ 0}, {1} times have been called", state, + +count);7         }8         Static voidMain (string[] args)9         {TenProgram P =NewProgram (); One             //2000 milliseconds to start call, 1000 milliseconds per interval ATimer timer =NewTimer (P.run,"Hello", -, +); -Console.WriteLine ("Timer Start"); -              the console.readline (); -         } -}

Execution Result:

Iii. delegate execution of asynchronous

Use a delegate to execute async, using a reference method, which can execute asynchronously if a delegate object has only one method in the invocation list (this method is a reference method). The delegate class has two methods Beginivoke and EndInvoke.

BeginInvoke : When the BeginInvoke method is executed, the thread pool gets a separate thread to execute the reference method. And immediately returns to the original thread a reference to an object that implements the IAsyncResult interface, which contains the state of the thread pool running the Async method, and the original thread continues execution, while the referencing method is executed in parallel in the thread of the pool.

EndInvoke : Gets the value returned by the asynchronous method call and frees the resource, which takes the return value of the Async method as its own return value.

3 modes of delegate execution of asynchronous programming:

 wait until complete (wait-until-done): When an asynchronous method is initiated, the original thread executes to EndInvoke and then resumes when the asynchronous method completes.

   Polling (polling): The original thread periodically checks whether the originating thread is complete (as determined by the IAsyncResult.IsCompleted property), and if not, proceeds to the task in the original thread.

  callback (callback): The original thread executes all the time, without waiting or checking whether the originating thread is complete, and after the reference method in the originating thread completes, the initiator thread invokes the callback method . The result of the asynchronous method is processed by the callback method before calling EndInvoke.

① Wait until completion mode

The original thread executes to EndInvoke, and waits if the asynchronous task is not completed

1     Delegate intMydel (intFirstintsecond);//Delegate Declaration2     class Program3     {4         Static intSum (intXinty)5         {6Thread.Sleep ( +);7             returnX +y;8         }9         Static voidMain (string[] args)Ten         { OneMydel del =Sum; A             //Invoke asynchronous operation (The third parameter is the callback function, and the fourth argument is the extra value) -IAsyncResult iar = Del. BeginInvoke (3,5,NULL,NULL); -              the             //dosomehing ... -              -             //☆☆☆ executes EndInvoke, if the reference method sum does not complete, the main thread waits for it to complete -             intresult =del. EndInvoke (IAR); + Console.WriteLine (result); -         } +}
② Polling Mode

Periodically query whether the task is complete:

1     Delegate intMydel (intFirstintsecond);//Delegate Declaration2     class Program3     {4         Static intSum (intXinty)5         {6Thread.Sleep ( +);7             returnX +y;8         }9         Static voidMain (string[] args)Ten         { OneMydel del =Sum; AIAsyncResult iar = Del. BeginInvoke (3,5,NULL,NULL); -              -             //☆☆☆ through the IAR. IsCompleted Regular query completion status the              while(!iar. iscompleted)//IsCompleted Indicates whether the invoked asynchronous operation is complete -             { -                 //dosomething -Thread.Sleep ( -); +Console.WriteLine ("no done"); -             } +             intresult =del. EndInvoke (IAR); A Console.WriteLine (result); at Console.readkey (); -         } -}

③ Callback Mode

After the original thread executes the BeginInvoke of the delegate, regardless of the new thread, the reference method in the delegate completes, obtains the result in the callback function and processes, executes the delegate's EndInvoke method

1     Delegate intMydel (intFirstintsecond);//Delegate Declaration2     class Program3     {4         Static intSum (intXinty)5         {6Thread.Sleep ( +);7             returnX +y;8         }9         Ten         //the signature and return value type of the callback method must be the same as the AsyncCallback delegate type One         //input parameter is IAsyncResult, return value is void type A        Static voidCallwhendone (IAsyncResult iar) { -AsyncResult AR =(AsyncResult) IAR; -Mydel del =(Mydel) ar. AsyncDelegate; the            intresult =del. EndInvoke (IAR); -Console.WriteLine ("callback function Execution EndInvoke"); -Console.WriteLine ("result:{0}", result); -Console.WriteLine ("callback function Complete"); +         }      -          +         Static voidMain (string[] args) A         { atMydel del =Sum; -             //The original thread is out of control after executing the BeginInvoke method, and the EndInvoke method is executed in the custom callback function (Callwhendone) -IAsyncResult iar = Del. BeginInvoke (3,5, Callwhendone,NULL); -Console.WriteLine ("starts a new thread, executes the callback function after the asynchronous task completes"); -             //dosomething -Console.WriteLine ("callback execution does not block the original thread"); in Console.readkey (); -         } to}

Execution Result:

There are other asynchronous programming patterns, such as BackgroundWorker, that are not discussed here.

  

C # Multithreading and Asynchrony (iii)--some asynchronous programming patterns

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.