C # Multi-Threading vs. async differences

Source: Internet
Author: User

With the popularization of multiple hard-threading CPUs (Hyper-threading, dual-core), concurrent programming methods such as multithreading and asynchronous operations are also more concerned and discussed. This article is mainly to discuss with the experts in the park how to use concurrency to maximize the performance of the program.

The similarities and differences between multithreading and asynchronous operations

Both multithreading and asynchronous operations can achieve the goal of avoiding calling thread blocking, thus improving the responsiveness of the software. Even sometimes we think that multithreading and asynchronous operations are the same concept. However, there are some differences between multithreading and asynchronous operations. These differences create the difference between the timing of using multithreading and asynchronous operations.

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 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.
Case study
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.
Example 1: 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.

using System;
using System.Threading;

namespace Asyncdelegatedemo
{
delegate void Asyncfoo (int i);
Class Program
{
///<summary>
/// output information for current thread
///</summary>
///<param name= "Name" > method name </param>

static void Printcurrthreadinfo (string name)
{
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" >sleep time </param>
static void Foo (int i)
{
Printcurrthreadinfo ("Foo ()");
Thread.Sleep (i);
}

///<summary>
/// post an asynchronous call
///</summary>
static void Postasync ()
{
Asyncfoo caller = new Asyncfoo (Foo);
caller. BeginInvoke (New AsyncCallback (Foocallback), caller);
}

static void Main (string[] args)
{
Printcurrthreadinfo ("Main ()");
for (int i = 0; i <; i++)
{
Postasync ();
}
console.readline ();
}

static void Foocallback (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 is not thread pool thread.
thread Id of Foo () Is:3, current thread is the thread pool thread.
thread Id of Foocallback () Is:3, current thread is the thread pool thread.
thread Id of Foo () Is:3, current thread is the thread pool thread.
thread Id of Foo () Is:4, current thread is the thread pool thread.
thread Id of Foo () Is:5, current thread is the thread pool thread.
thread Id of Foocallback () Is:3, current thread is the thread pool thread.
thread Id of Foo () Is:3, current thread is the thread pool thread.
thread Id of Foocallback () Is:4, current thread is the thread pool thread.
thread Id of Foo () Is:4, current thread is the thread pool thread.
thread Id of Foo () Is:6, current thread is the thread pool thread.
thread Id of Foocallback () Is:5, current thread is the thread pool thread.
thread Id of Foo () Is:5, current thread is the thread pool thread.
thread Id of Foo () Is:7, current thread is the thread pool thread.
thread Id of Foocallback () Is:3, current thread is the thread pool thread.
thread Id of Foo () Is:3, current thread is the thread pool thread.
thread Id of Foocallback () Is:4, current thread is the thread pool thread.
thread Id of Foocallback () Is:6, current thread is the thread pool thread.
thread Id of Foocallback () Is:5, current thread is the thread pool thread.
thread Id of Foocallback () Is:7, current thread is the thread pool thread.
thread Id of Foocallback () Is:3, current thread is the thread pool thread.

As you can see from the output, the asynchronous calls that. NET uses delegate to "automatically" generate are using additional threads (and thread pool threads).

C # Multi-Threading vs. async differences

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.