C # Multi-Threading vs. asynchronous invocation

Source: Internet
Author: User

The nature of asynchronous operations

Specifies a callback function for the Async method before the method call, which is executed by a thread in the thread pool after the method call. The main thread returns immediately, continuing to perform other work or responding to user requests. If the Async method finishes executing, the callback function is automatically executed to handle the invocation result of the asynchronous method. How do you implement asynchronous methods? C # implements asynchronous methods by invoking the BeginInvoke and EndInvoke methods with asynchronous delegates.

BeginInvoke method Prototype: IAsyncResult BeginInvoke (..., AsyncCallback callback, Object o); ...... Represents a list of parameters defined in an asynchronous delegate. The AsyncCallback parameter is a delegate for the callback function, which is prototyped as: public delegate void AsyncCallback (IAsyncResult ar). Where the IAsyncResult parameter is used to wrap the execution result of an async method. The object parameter is used to pass some additional information, such as synchronizing information, between the main thread and the callback function.

EndInvoke method prototype: XXX EndInvoke (IAsyncResult result); XXX represents the return data type defined in the asynchronous delegate prototype, and IAsyncResult is used to wrap the execution results of the Async method.

  The nature of Threads
A thread is not a function of a computer's hardware, but rather a logical function provided by the operating system, which is essentially a piece of code that runs concurrently in a process, so the thread requires the operating system to run and dispatch the CPU resources.

  Advantages and disadvantages of asynchronous operations

Because asynchronous operations do not require additional thread burdens and are handled in a callback manner, the processing function can eliminate the possibility of deadlocks by eliminating the need for shared variables (even if it is not completely unused, at least by reducing the number of shared variables). Of course, asynchronous operations are not flawless. Writing asynchronous operations is a high degree of complexity, the program mainly uses callback method to handle, and ordinary people's way of thinking some first, and difficult to debug.

  Advantages and disadvantages of multithreading
The advantages of multithreading are obvious, the handlers in the thread are still sequential execution, in line with the normal thinking habits, so programming is simple. However, the disadvantage of multithreading is equally obvious, the use of threads (misuse) will bring the burden of context switching to the system. Also, shared variables between threads can cause deadlocks to occur.

  Scope of application

After understanding the pros and cons of threading and asynchronous operations, we can explore the logical use of a thread and async. I think that when I am required to perform I/O operations, it is more appropriate to use asynchronous operations than to use thread + synchronous I/O operations. I/O operations include not only direct files, read and write to the network, but also database operations, Web Service, HttpRequest, and cross-process calls such as. Net Remoting.
The scope of the thread is the kind that requires long CPU operations, such as long-time graphics processing and algorithm execution. But often because of the simple and consistent use of threading programming, many friends tend to use threads to perform long-time I/O operations. This is harmless when there are only a few concurrent operations, which is not appropriate if you need to handle a large number of concurrent operations.

Here's an example of an asynchronous invocation:

usingSystem;usingSystem.Threading;namespaceasyncdelegatedemo{Delegate voidAsyncfoo (inti); classProgram {///<summary>    ///output information for the current thread///</summary>   ///<param name= "name" >Method Name</param>    Static voidPrintcurrthreadinfo (stringname) {Console.WriteLine ("Thread Id of"+ name+"is :"+ thread.currentthread.managedthreadid+", current thread is"+ (Thread.CurrentThread.IsThreadPoolThread?)"":" not")      +"thread pool thread."); }    ///<summary>    ///test method, sleep for a certain time///</summary>    ///<param name= "I" >the time of sleep</param>    Static voidFoo (inti) {printcurrthreadinfo ("Foo ()");    Thread.Sleep (i); }    ///<summary>    ///post an asynchronous call///</summary>    Static voidPostasync () {Asyncfoo caller=NewAsyncfoo (Foo); Caller. BeginInvoke ( +,NewAsyncCallback (Foocallback), caller); }    Static voidMain (string[] args) {Printcurrthreadinfo ("Main ()");  for(inti =0; I <Ten; i++) {Postasync ();    } console.readline (); }    Static voidfoocallback (IAsyncResult ar) {printcurrthreadinfo ("Foocallback ()"); Asyncfoo Caller=(Asyncfoo) ar.      asyncstate; Caller.    EndInvoke (AR); }  }}  

The output of this code is as follows:

Thread Id of Main () is:1, Current thread isNot thread pool thread. Thread Id of Foo () is:3, Current thread isthread pool thread. Thread Id of Foocallback () is:3, Current thread isthread pool thread. Thread Id of Foo () is:3, Current thread isthread pool thread. Thread Id of Foo () is:4, Current thread isthread pool thread. Thread Id of Foo () is:5, Current thread isthread pool thread. Thread Id of Foocallback () is:3, Current thread isthread pool thread. Thread Id of Foo () is:3, Current thread isthread pool thread. Thread Id of Foocallback () is:4, Current thread isthread pool thread. Thread Id of Foo () is:4, Current thread isthread pool thread. Thread Id of Foo () is:6, Current thread isthread pool thread. Thread Id of Foocallback () is:5, Current thread isthread pool thread. Thread Id of Foo () is:5, Current thread isthread pool thread. Thread Id of Foo () is:7, Current thread isthread pool thread. Thread Id of Foocallback () is:3, Current thread isthread pool thread. Thread Id of Foo () is:3, Current thread isthread pool thread. Thread Id of Foocallback () is:4, Current thread isthread pool thread. Thread Id of Foocallback () is:6, Current thread isthread pool thread. Thread Id of Foocallback () is:5, Current thread isthread pool thread. Thread Id of Foocallback () is:7, Current thread isthread pool thread. Thread Id of Foocallback () is:3, Current thread isThread pool thread.

C # Multi-Threading vs. asynchronous invocation

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.