Analysis on the implementation principle of Visual Studio async CTP-jump out of the task and build your own awaiter

Source: Internet
Author: User

After reading the previous article, we know that the await keyword is followed by a task object, although to look like a real method, the extension methods added by the async CTP class library for existing objects do not use typical get/make words. A more accurate statement is that await should be followed by an await object, or an object that has a public getawaiter () method and can return the awaiter object. The so-called awaiter object is slightly different from our previous saying, because it is the syntactic sugar at the compiler layer, the awaiter object has no practical significance. For example, if an iawaitable interface is implemented, it only requires a beginawait and endawait method.

See the followingCodeFragment:

 
1:Await 1000;

We hope to wait 1000 milliseconds asynchronously. Of course, the compiler does not politely reject our requirements because an awaiter cannot be obtained from the number 1000 (for simplicity, we will follow this statement later, the correct statement should be that the beginawait and endawait methods are not found.) to achieve our goal, we use the task to add a getawaiter Method to the INT:

 
1:Public Static ClassIntextensions
2:{
 
3:Public StaticTaskawaiter <Int> Getawaiter (This IntS)
 
4:{
 
5:Taskcompletionsource <Int> TSC =NewTaskcompletionsource <Int> ();
 
6:Task <Int> Task = TSC. task;
 
7: 
 
8:TSC. trysetresult (0 );
 
9: 
10:ReturnTask. getawaiter <0> ();
 
11:}
 
12:}

In this way, await 1000 is recognized by the compiler that our code can be executed smoothly, but we have not yet specified the task to execute. We need to wait 1000 milliseconds, so await will return immediately. Task content is not involved here. We use another method to implement beginawait and endawait directly for the int type, or define an intawaiter class separately. The above code is simply modified:

 
1:Public StaticIntawaiter getawaiter (This IntI)
 
2:{
 
3:Return NewIntawaiter (I );
 
4:}

The intawaiter class is defined as follows:

 
1:Public ClassIntawaiter
 
2:{
3:Synchronizationcontext _ uicontext = synchronizationcontext. Current;
 
4: 
 
5:Int_ Value = 0;
 
6: 
 
7:PublicIntawaiter (IntI)
 
8:{
 
9:_ Value = I;
 
10:}
 
11: 
 
12:Public BoolBeginawait (Action continuation)
13:{
 
14:If(Synchronizationcontext. Current! = _ Uicontext)
 
15:{
 
16:Return False;
 
17:}
 
18:Else
 
19:{
 
20:Threadpool. queueuserworkitem (state) =>
 
21:{
 
22:Thread. Sleep (_ value );
23:_ Value = 5;
 
24:_ Uicontext. Send (NewSendorpostcallback (target) =>{ continuation ();}),Null);
 
25:});
 
26:Return True;
 
27:}
 
28:}
 
29: 
 
30:Public IntEndawait ()
 
31:{
32:Return_ Value;
 
33:}
 
34:}

Then let's write a few codes to test:

1:Listbox1.items. Add (datetime. Now );
 
2:Await 1000;
 
3:Listbox1.items. Add (datetime. Now );
 
4:Await 5000;
 
5:Listbox1.items. Add (datetime. Now );

The result is as follows:

Intawaiter is very simple. In fact, the taskawaiter in async CTP basically does these tasks. Start the task in beginawait and judge the task status in endawait. if the task is completed successfully, returns the result object of a task. If it is cancel or fault, an exception is thrown.

As mentioned in the previous article, if an Asynchronous Method in an application is implemented by itself rather than a proxy class automatically generated by Vs like WCF, in this case, we can fully process async in the code to achieve the code style that is as concise as await, rather than let the compiler do this. After all, if it is not true, it cannot replace the guy I don't want to include K, in addition, the failure of await debugging in preview is also a headache.

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.