C # Asynchronization and Synchronization,

Source: Internet
Author: User

C # Asynchronization and Synchronization,

When it comes to Asynchronization, what does it correspond? Synchronization. So how does C # asynchronous and synchronous work?

First, let's take a look at the chestnuts:

Create a console application and add the following code to the Program file:

1 static void Main (string [] args) 2 {3 // timer 4 Stopwatch watch = new Stopwatch (); 5 // start timing 6 watch. start (); 7 Console. writeLine ($ "{DateTime. now. toString ()} enters the Main method, and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); 8 // call Task 1 (synchronous) 9 TaskOne (); 10 // call Task 2 11 TaskTwo (); 12 // stop the timer 13 watch. stop (); 14 Console. writeLine ($ "{DateTime. now. toString ()} exit the Main method. Execution thread: {System. threading. thread. currentThread. managedThreadId} "); 15 Console. writeLine ($ "Total time consumed by the main thread: {watch. elapsedMilliseconds} ms "); 16 Console. readKey (); 17} 18 19 /// <summary> 20 // Task 1 21 /// </summary> 22 static void TaskOne () 23 {24 Console. writeLine ($ "{DateTime. now. toString ()} enters the TaskOne method, and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); 25 for (int I = 0; I <5; I ++) 26 {27 Console. writeLine ($ "{DateTime. now. toString ()} TaskOne is being executed. Execution thread: {System. threading. thread. currentThread. managedThreadId} "); 28 System. threading. thread. sleep (1000); 29} 30 Console. writeLine ($ "{DateTime. now. toString ()} exit the TaskOne method and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); 31} 32 // <summary> 33 // Task 2 34 /// </summary> 35 static void TaskTwo () {36 Console. writeLine ($ "{DateTime. now. toString ()} enters the TaskTwo method, and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); 37 for (int I = 0; I <2; I ++) 38 {39 Console. writeLine ($ "{DateTime. now. toString ()} TaskTwo is being executed. Execution thread: {System. threading. thread. currentThread. managedThreadId} "); 40 System. threading. thread. sleep (1000); 41} 42 Console. writeLine ($ "{DateTime. now. toString ()} Exits the TaskTwo method and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); 43}

This Chestnut is very simple. Two methods are defined: TaskOne and TaskTwo. Output the current time and current thread every second. TaskOne loops for five times and TaskOne2 times. Then, call the MAIN function sequentially, and record the total execution time of the MAIN function. F5 Running Effect

We can see that after the program executes TaskOne sequentially, it executes TaskTwo again. The execution thread has not changed.

Next we will change the code and rewrite TaskOne asynchronously. When it comes to Asynchronization, I think it will come to my mind. Keyword async. Of course, await can be paired with it. Let's take a look at the rewritten code:

/// <Summary> /// Task 1 (asynchronous) /// </summary> /// <returns> </returns> static async Task <int> TaskOneAsync () {Console. writeLine ($ "{DateTime. now. toString ()} enters the TaskOneAsync method, and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); var t = Task <int>. run () => {var total = 0; for (int I = 0; I <5; I ++) {total ++; Console. writeLine ($ "{DateTime. now. toString ()} TaskOneAsync is being executed. Execution thread: {System. threading. thread. currentThread. managedThreadId} "); System. threading. thread. sleep (1000);} return total;}); Console. writeLine ($ "{DateTime. now. toString ()} Exits the TaskOneAsync method and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); return await t ;}

The main function calls the asynchronous method instead.

Static void Main (string [] args) {// timer Stopwatch watch = new Stopwatch (); // start timer watch. start (); Console. writeLine ($ "{DateTime. now. toString ()} enters the Main method, and the execution thread is {System. threading. thread. currentThread. managedThreadId} "); // call Task 1 (synchronous) // TaskOne (); // call Task 1 (asynchronous) TaskOneAsync (); // call Task 2 TaskTwo (); // stop the timer watch. stop (); Console. writeLine ($ "{DateTime. now. toString ()} exit the Main method. Execution thread: {System. threading. thread. currentThread. managedThreadId} "); Console. writeLine ($ "Total time consumed by the main thread: {watch. elapsedMilliseconds} ms "); Console. readKey ();}

Effect after running F5:

We can see that the execution time of Main function is changed from 7082ms to 2404 ms. The time is greatly shortened. However, after the main is finished, TaskOneAsync is still running... and the execution thread of TaskOneAsync is 10 instead of the main thread 9 !!

Next, let's take a good look at the execution process of the program:

 

It can be seen that when the program enters the Main method for execution and enters TaskOneAsync, the thread ID is still 9. When a Task is executed to create and run. The main thread is not blocked, but a new thread 10 is opened separately to execute the TASK. The main thread is still executed sequentially and then exits the Asynchronous Method. The Task is executed in TaskTwo and ends until the end of the Main method. Because TaskOneAsync takes a long time, thread 10 continues to execute the Task. Until the Task ends. In fact, when the Task is Run, a new thread has been opened to execute the Task in the Task, and the main thread continues to execute TaskTwo. During the execution of TaskTwo, task TaskOneAsync is also executed in another thread at the same time. It can be seen that the Task will open a new thread to execute commands, and the current thread will not be blocked. Therefore, the Main thread does not actually execute the tasks in the most time-consuming TaskOneAsync in the same way as synchronization, instead, it is handed over to another thread for execution. This is the reason why the execution time of the main thread is greatly shortened. Therefore, this processing mechanism is user-friendly for user experience. In fact, in our development, we often see Methods ending with async. The most common methods are IO reading, writing, and library methods related to http resource requests. These are time-consuming and generally time-consuming tasks. In order not to affect the response of the main thread, we generally adopt asynchronous processing.

Then, when the main thread needs to obtain the results returned by the Task, the main thread will block the thread and wait until the results are returned before continuing to execute. Change the code in the Main method to verify the Code:

The main thread blocks the thread and waits until the Task is executed.

In summary, asynchronous and synchronous, I understand it as follows:

Synchronization: A Code instruction is executed in sequence on the same thread, and there is no queue in the middle. Like buying tickets at a cinema, there are many people (commands to be executed), but there is only one window (one thread, usually the main thread ). The people behind the ticket can only wait for the previous person to buy the ticket. The previous step is the same. Therefore, it is called synchronization.

Asynchronous: A Code instruction. During execution, some of the commands are executed at the same time as the command, but the threads used to operate on them are different. The two are parallel for a period of time. For example, when there are more and more people waiting to buy tickets in the cinema, the manager immediately arranged a new ticket conductor to open a new window (with a new thread) to sell tickets ), A part has been transferred to the new window to continue queuing for tickets. In this way, the job and time of the original ticket window (main thread) are reduced accordingly.

Asynchronous mode is actually a processing mechanism, which has advantages and disadvantages. If we abuse it without reason, it will be counterproductive. Because newly opened threads consume thread resources. Therefore, we adhere to the principle that, without affecting the response of the main thread, we do not need to use it.

All of the above are my personal opinions. If you have any mistakes, I hope you can give me some advice ~~

 

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.