Async and await keywords for asynchronous programming

Source: Internet
Author: User
Tags call back

Concept

The asynchronous programming core is an asynchronous operation that, once started, is completed over a period of time. The so-called asynchronous, the key is to achieve two points: (1) is performing this operation, does not block the original thread (2) Once started this operation, you can continue to perform other tasks. When the operation completes, a callback function is called to notify that the operation has ended.

"Note": I always think that both synchronous and asynchronous belong to the category of multi-threaded, to today only understand the complete error, asynchronous and multi-threaded is a different category, multithreading and asynchronous is the two forms of concurrency, parallel processing and thread synchronization is the two forms of multithreading, this is my current understanding, I do not know whether the error, if there are errors Please make bricks and correct, the first study inevitably wrong, hope Haihan!

So the question is, why is asynchronous programming efficient? The first thing you need to know is that "IO Operation DMA (direct memory access) mode" is a data exchange Mode that directly accesses memory data without CPU. The data exchange through DMA can hardly deplete the CPU's resources. The asynchronous programming model provided by the CLR takes advantage of the DMA capabilities of the hardware to relieve the pressure on the CPU.

Async and await keywords for asynchronous programming

General usage: Add the Async keyword to the method declaration, which is intended to make the keyword await in the method take effect (in order to maintain backward compatibility, and also introduce the two keywords), if the Async method has a return value, return Task<t>, if not, return a task, The purpose of returning these tasks is to notify the end of the main program async method. Let's use these two keywords to introduce some of the usage examples!

1 async Task Dosomethingasync () 2 {3 int val = 13; 4//Async wait 1 seconds 5 await Task.delay (Timespan.fromseconds (1)); 6 Val *= 2 ; 7//Async wait 1 seconds 8 await Task.delay (Timespan.fromseconds (1)); 9 Trace.WriteLine (val); 10}

In the WinForm program, add a button and label text, and the Click event code for this button is:

1         private void Btnsync_click (object sender, EventArgs e) 2         {3             dosomethingsync (); 4             Label1. Text = "Async done"; 5         }

"Issue 1" When this button is clicked, the Async method is executed before output 26, then the Label1 is executed. text= "Aysnc done"? The answer is no!. Because async executes synchronously at the beginning, an asynchronous wait is performed inside its method because the AWAIT keyword exists! But before that, it first checks to see if the operation is complete and, if it is done, continues to run synchronously! Otherwise, the Async method is paused and returned, leaving the unfinished task behind. After a while the operation completes, the Async method resumes running! Don't you understand? The popular point is that when a click event is triggered, the asynchronous method is executed first, and a new worker thread in the thread pool is started, but the main thread is not blocked from running, so this will return an unfinished task in an async method, first executing the following sentence Label1. text= "Async done" until the task finishes with output 26!

"Question 2" if the above event is written as follows, what will be the result? The conclusion is that the asynchronous method output 26 is executed first, and then the Label1 is executed. text= "AYSNC done!

      Private async void Btnsync_click (object sender, EventArgs e)        {            await dosomethingsync ();            Label1. Text = "Async done";        }

This is equivalent to the async nested, click to trigger the asynchronous event, execute the asynchronous method Dosomethinsync, so it will be a new worker thread, does not affect the main thread of the run, but at this time the main thread is the asynchronous event, the first execution of the method after the output of 26 and then execute the output text Label1. Text = "Async done";

So the await keyword works by: A new worker thread in the thread pool will be executed, and when the IO operation is performed, the worker thread is returned to the thread pool, so the method that the await is located on is not blocked. After this task is completed, the code after that keyword is executed!

About Async Methods Async

An async method is composed of several blocks of synchronous execution, each of which is isolated by await! So, for this reason, each Synchronizer block tries to resume running in the original context, that is, if the Dosomethinsync method is called in the UI thread, it will run in the UI thread, and if it is called in the thread pool, it will be run in the threads of the online pools! This is certainly not the result we want, we need to run it in the calling thread and avoid the wrong behavior.

For the above async methods, only such modifications can be task.delay in asynchronous Waits (Timespan.fromseconds (1)). Configureawait (FALSE); For configureawait to True, the method that you call is returned to the original context to run! After this is set, this will run in the calling thread.

About Task Tasks

(1) requires the CPU to actually execute the command, when creating the task of such calculation, use Task.run, if you need to follow a specific plan to use Taskfactory.startnew

(2) Tasks that require notification-based (notification) events and most require IO operations, use taskcompletionsource<t>

Summary (1) Where asynchronous programming requires attention

"1" If you use the Async async method, it is best to use it all the time, and then call back the task object returned to the end to avoid using task.wait or TASK<T> Result method because it is extremely easy to create a deadlock.

"2" Do not use void as the return type of the Async Method! The Async method can return void, but this is limited to writing event handlers. A normal Async method returns TASK<T> If there is a return value, and if there is no return value, the task is returned instead of void!

"3" has been using configureawait in the core library code. In the peripheral user interface code, the context is restored only when needed.

(2) References

"1" C # concurrent Programming Classic Instance

"2" garden a friend in C # Concurrent programming Classic instance of the annotations, really can not find the friend link, here to express thanks

Tags: C #, concurrent programming

Async and await keywords for asynchronous programming

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.