The difference between async and multithreading in C #

Source: Internet
Author: User

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 with asynchronous and multithreaded differences

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 the thread of the difference between async and multithreading

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.

The advantages and disadvantages of asynchronous and multi-threaded differences between async 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.

The pros and cons of multiple threads that differ between asynchronous and multithreaded

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.

A case study of the difference between asynchronous and multithreading

Having said something so theoretically, some brothers may have been impatient for a long time, so let's look at a couple of practical examples of asynchronous operations.

Examples of asynchronous and multithreaded differences: What is the asynchronous method generated by delegate?

As you may all know, using delegate can "auto" make a method asynchronous call. Intuitively, I think the compiler or the CLR used another thread to execute the target method. Is that what it is? Let's prove it with a piece of code.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 usingSystem;  usingSystem.Threading;namespaceAsyncDelegateDemo{    delegatevoidAsyncFoo(int i);    classProgram    {        /// ﹤summary﹥          /// 输出当前线程的信息          /// ﹤/summary﹥             /// ﹤param name="name"﹥方法名称﹤/param﹥           staticvoidPrintCurrThreadInfo(stringname)        {            Console.WriteLine("Thread Id of " + name + " is: "+ Thread.CurrentThread.ManagedThreadId + ", current thread is "                + (Thread.CurrentThread.IsThreadPoolThread ? "": "not ") + "thread pool thread.");        }        /// ﹤summary﹥          /// 测试方法,Sleep一定时间          /// ﹤/summary﹥          /// ﹤param name="i"﹥Sleep的时间﹤/param﹥          staticvoidFoo(inti)        {            PrintCurrThreadInfo("Foo()");             Thread.Sleep(i);        }         /// ﹤summary﹥          /// 投递一个异步调用          /// ﹤/summary﹥          staticvoidPostAsync()        {            AsyncFoo caller = newAsyncFoo(Foo);            caller.BeginInvoke(1000, newAsyncCallback(FooCallBack), caller);        }        static voidMain(string[] args)        {            PrintCurrThreadInfo("Main()");            for(inti = 0; i < 100; i++)            {                PostAsync();            }             Console.ReadLine();        }         staticvoidFooCallBack(IAsyncResult ar)        {            PrintCurrThreadInfo("FooCallBack()");            AsyncFoo caller = (AsyncFoo)ar.AsyncState;             caller.EndInvoke(ar);        }    }}

The output of the example code for asynchronous and multithreaded differences is as follows:

Thread Id of Main () is:1,

The current thread is the not thread pool thread.

Thread Id of Foo () Is:3,

The current thread is the thread pool thread.

Thread Id of Foocallback () Is:3,

The current thread is the thread pool thread.

Thread Id of Foo () Is:3,

The current thread is the thread pool thread.

Thread Id of Foo () Is:4,

The current thread is the thread pool thread.

Thread Id of Foo () Is:5,

The current thread is the thread pool thread.

Thread Id of Foocallback () Is:3,

The current thread is the thread pool thread.

Thread Id of Foo () Is:3,

The difference between async and multithreading in C #

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.