What is the difference between async and multithreading in C #? Both asynchronous and multi-threaded can achieve the goal of avoiding calling thread blocking, thus improving the responsiveness of the software. Even sometimes we think that async and multithreading are the same concepts. However, there are some differences between async and multithreading. These differences lead to the use of asynchronous and multi-threaded timing differences.
The nature of asynchronous operations
All programs will eventually be executed by the computer hardware, so in order to better understand the nature of the asynchronous operation, we need to understand its hardware base. Familiar with the computer hardware friend is certainly not unfamiliar with the word DMA, hard disk, optical drive technical specifications have a clear DMA mode indicator, in fact, the network card, sound card, video card also has DMA function. DMA is the meaning of direct memory access, which means that the DMA-capable hardware does not consume CPU resources when exchanging data with the memory. As long as the CPU sends an instruction when it initiates the data transfer, the hardware begins to exchange data between itself and the memory, and after the transfer is complete, the hardware triggers an interrupt to notify the operation to complete. These I/O operations that do not consume CPU time are the hardware basis for asynchronous operations. Therefore, even in a single process such as DOS (and the Wireless Path concept) system can also initiate asynchronous DMA operation.
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 using callback methods to handle, and ordinary people's way of thinking, 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.
There are 4 ways to implement asynchronous programming, and these 4 kinds of adapting actually correspond to 4 types of asynchronous calls, which are divided into "wait" and "callback" classes.
Callbacks, of course, belong to the "callback" class. Recommended!!!!
The previous three methods were waiting for the asynchronous method to complete before they could get the result of the execution, while the main thread was waiting. The biggest difference is that when calling BeginInvoke, the main thread will not have to wait for the asynchronous thread to finish, and the asynchronous thread will invoke the callback method we provided at the end of the work and handle the callback method accordingly.
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;namespace Summary of asynchronous invocation implementation methods 4{//<summary>///////4. Callback////Three methods before the execution of the asynchronous method, the main thread is in wait state. The biggest difference is that when calling BeginInvoke, the main thread is not required to wait for the asynchronous thread to finish, and/or the asynchronous thread will invoke the callback method we provided at the end of the work, and handle the callback method accordingly. For example, displays the result of an asynchronous call. </summary> class Program {public delegate void Printdelegate (string s); static void Main (string[] args) {printdelegate printdelegate = Print; Console.WriteLine ("Main thread."); Printdelegate.begininvoke ("Hello World", Printcomeplete, printdelegate); Console.WriteLine ("Main thread continues execution ..."); Console.WriteLine ("Press any key to continue ..."); Console.readkey (TRUE); public static void Print (String s) {Console.WriteLine ("Current thread:" +s); Thread.Sleep (5000); }//callback method requires//1. return type void//2. There is only one parameter IAsyncResult public static void Printcomeplete (IAsyncResult result) {(result). AsyncState as Printdelegate). EndInvoke (result); Console.WriteLine ("Current thread ends." + result.) Asyncstate.tostring ()); } }}
Note that the code has been noted, the program operation results are as follows:
The first method: The Beginenvoke Endenvoke method, which belongs to the "Wait" class.
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;namespace Asynchronous Call implementation method Rollup {///<summary>//////1.BeginEnvoke Endenvoke////+/+//: When using BeginInvoke to invoke the method asynchronously, if the method is not executed, E The Ndinvoke method will block until the called method finishes executing///</summary> class Program {public delegate void Printdelegate (Stri ng s); static void Main (string[] args) {printdelegate printdelegate = Print; Console.WriteLine ("Main thread"); IAsyncResult result= Printdelegate.begininvoke ("Hello World", NULL, NULL); Console.WriteLine ("Main thread continues execution ..."); When using BeginInvoke to invoke the method asynchronously, if the method is not finished, the EndInvoke method will block until the called method executes Printdelegate.endinvoke (result); Console.WriteLine ("Press any key to continue ..."); Console.readkey (TRUE); public static void Print (String s) {Console.WriteLine ("Asynchronous Thread starts execution:" +s); Thread.Sleep (5000); } }}
Note that the code has been noted, the program operation results are as follows:
The second method: WaitOne. Also belongs to the "Wait" class.
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;namespace Just use the WaitOne function code EndInvoke only. ///</summary> class Program {public delegate void Printdelegate (string s); static void Main (string[] args) { printdelegate printdelegate = Print; Console.WriteLine ("Main thread"); IAsyncResult result = Printdelegate.begininvoke ("Hello World", NULL, NULL); Console.WriteLine ("Main thread continues execution ..."); Result. Asyncwaithandle.waitone ( -1, false); Console.WriteLine ("Press any key to continue ..."); Console.readkey (True); } public static void Print (string s) { Console.WriteLine ("Asynchronous Thread Begins execution:" + s); Thread.Sleep ();}}}
Note that the code has been noted, the program operation results are as follows:
The third method: polling. Also belongs to the "Wait" class.
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;namespace Summary of asynchronous invocation implementation methods 3{//<summary>///////3. Polling/////+//+//+//(+//) The two methods mentioned before, can only wait until the asynchronous method is executed,///before the completion of the process, the entire program Like no response, the user experience is not good,//////You can check the completion of an asynchronous call by checking the IsCompleted property of the IAsyncResult type, or///if it is not completed, you can display some information in a timely manner//</summary> Class Program {public delegate void Printdelegate (string s); static void Main (string[] args) {printdelegate printdelegate = Print; Console.WriteLine ("Main thread:" +thread.currentthread.managedthreadid); IAsyncResult result = Printdelegate.begininvoke ("Hello World", NULL, NULL); Console.WriteLine ("Main thread:" + Thread.CurrentThread.ManagedThreadId + ", continue execution ..."); while (!result. iscompleted) {Console.WriteLine ("."); Thread.Sleep (500); } Console.WriteLine ("Main thread:" + Thread.CurrentThread.ManagedThreadId +"Press any key to continue ..."); Console.readkey (TRUE); } public static void Print (String s) {Console.WriteLine ("Current thread:" + Thread.CurrentThread.ManagedTh Readid + s); Thread.Sleep (5000); } }}
Note that the code has been noted, the program operation results are as follows:
. NET Asynchronous Programming callbacks