C # differences between multithreading and Asynchronization

Source: Internet
Author: User

With the popularization of multiple hard-threaded CPUs (hyper-threading and dual-core), the design methods of concurrent programs such as multithreading and asynchronous operations have also received more attention and discussion. This article mainly aims to discuss with the masters in the garden how to use concurrency to maximize program performance.

  Similarities and differences between multithreading and asynchronous operations

Both multithreading and asynchronous operations can avoid calling thread blocking and improve software responsiveness. Sometimes we think that multithreading and asynchronous operations are equivalent. However, there are some differences between multithreading and asynchronous operations. These differences lead to the difference between the timing of using multithreading and asynchronous operations.

  Nature of asynchronous operations

All programs will eventually be executed by computer hardware. Therefore, to better understand the nature of asynchronous operations, we need to understand its hardware base. Friends who are familiar with computer hardware must be familiar with the DMA term. The technical specifications of hard disks and optical drives all have clear DMA mode indicators. In fact, NICS, sound cards, and video cards also have DMA functions. DMA means direct access to memory. That is to say, hardware with DMA functions can exchange data with memory without consuming CPU resources. As long as the CPU sends a command when initiating data transmission, the hardware starts to exchange data with the memory. After the transmission is complete, the hardware triggers an interruption to notify the operation to complete. These I/O operations that do not consume CPU time are the hardware basis of asynchronous operations. Therefore, asynchronous DMA operations can be initiated even in a single process (and wireless process) system such as DOS.

  Thread nature

A thread is not a computer hardware function, but a logic function provided by the operating system. A thread is essentially a piece of code that runs concurrently in a process, therefore, threads require the operating system to invest CPU resources for running and scheduling.

  Advantages and disadvantages of asynchronous operations

Because asynchronous operations do not require additional thread burden and Use callback for processing, the processing function does not need to use shared variables (even if it cannot be completely used, at least the number of shared variables can be reduced) to reduce the possibility of deadlocks. Of course, asynchronous operations are not perfect. It is highly complex to write asynchronous operations. The program mainly uses the callback method for processing, which is a bit difficult to debug with the way of thinking of ordinary people.

  Advantages and disadvantages of Multithreading

The advantages of multithreading are obvious. The processing program in the thread is still executed in sequence, which conforms to the thinking habits of ordinary people, So programming is simple. However, the disadvantages of multithreading are also obvious. The use (abuse) of threads will impose additional burden on context switching. In addition, shared variables between threads may cause deadlocks.

  Applicability

After understanding the advantages and disadvantages of threads and asynchronous operations, we can discuss the rational use of threads and asynchronous operations. In my opinion, when I/O operations are required, it is more appropriate to use asynchronous operations than to use thread + synchronous I/O operations. I/O operations include not only direct file and network read/write operations, but also cross-process calls such as database operations, Web Service, httprequest, And. Net remoting.

The applicability of threads is those that require long CPU operations, such as time-consuming graphics processing and Algorithm Execution. However, due to the simplicity and habit of using thread programming, many friends often use threads to execute time-consuming I/O operations. In this way, there are only a few concurrent operations, but it is not suitable if you need to handle a large number of concurrent operations.

  Instance research

Some brothers may have been impatient with the theory. Now let's look at several practical asynchronous operation examples.

  Example 1: What is the asynchronous method generated by Delegate?

As you may know, using delegate can "automatically" enable asynchronous calls to a method. Intuitively, I think the compiler or CLR uses another thread to execute the target method. Is that true? Let's use a piece of code to prove it.

Using system;
Using system. Threading;

Namespace asyncdelegatedemo
{
Delegate void asyncfoo (int I );
Class Program
{
/// <Summary>
/// Output the information of the 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 period of time
/// </Summary>
/// <Param name = "I"> sleep time </param>
Static void Foo (int I)
{
Printcurrthreadinfo ("Foo ()");
Thread. Sleep (I );
}

/// <Summary>
/// Deliver an asynchronous call
/// </Summary>
Static void postasync ()
{
Asyncfoo caller = new asyncfoo (FOO );
Caller. begininvoke( 1000, new asynccallback (foocallback), caller );
}

Static void main (string [] ARGs)
{
Printcurrthreadinfo ("Main ()");
For (INT I = 0; I <10; 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 thread pool thread.

Thread ID of foocallback () is: 3, current thread is thread pool thread.

Thread ID of Foo () is: 3, current thread is thread pool thread.

Thread ID of Foo () is: 4, current thread is thread pool thread.

Thread ID of Foo () is: 5, current thread is thread pool thread.

Thread ID of foocallback () is: 3, current thread is thread pool thread.

Thread ID of Foo () is: 3, current thread is thread pool thread.

Thread ID of foocallback () is: 4, current thread is thread pool thread.

Thread ID of Foo () is: 4, current thread is thread pool thread.

Thread ID of Foo () is: 6, current thread is thread pool thread.

Thread ID of foocallback () is: 5, current thread is thread pool thread.

Thread ID of Foo () is: 5, current thread is thread pool thread.

Thread ID of Foo () is: 7, current thread is thread pool thread.

Thread ID of foocallback () is: 3, current thread is thread pool thread.

Thread ID of Foo () is: 3, current thread is thread pool thread.

Thread ID of foocallback () is: 4, current thread is thread pool thread.

Thread ID of foocallback () is: 6, current thread is thread pool thread.

Thread ID of foocallback () is: 5, current thread is thread pool thread.

Thread ID of foocallback () is: 7, current thread is thread pool thread.

Thread ID of foocallback () is: 3, current thread is thread pool thread.


From the output, we can see that. net uses delegate to automatically generate asynchronous calls using another thread (It is also a thread pool thread.).

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.