Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must "await" be inside an "async" method? [duplicate]

Tags:

c#

async-await

Possible Duplicate:
Why does the async keyword exist

I have two methods. One is a normal method (MyMethod) and one is an async method (MyMethodAsync). I get a compilation error.

static string MyMethod()
{
    var result = await MyMethodAsync(); // compile error here
    return result;
}

async static Task<string> MyMethodAsync()
{
    /** perform my logic here... **/
    Thread.Sleep(1000);

    return "yes";
}

The error message is

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

I'm confused. When I use the await keyword, the calling thread will be suspended and wait for task completion. So once await is in use, the method is no longer an async method. Right?

Remark: I know I should put the logic in MyMethod and MyMethodAsync calls MyMethod to achieve what I want.

like image 714
Alex Yeung Avatar asked Dec 03 '12 00:12

Alex Yeung


2 Answers

The entire point of the async keyword is to enable the await keyword.

I collected a number of "why do the keywords work that way?" questions on my blog. The question of "why can't async be inferred by the presence of await?" was answered conclusively by Eric Lippert on his blog. In short, two reasons: backwards compatibility and code readability.

like image 112
Stephen Cleary Avatar answered Oct 24 '22 17:10

Stephen Cleary


For a huge amount of insight as to how async and await work internally, check out Jon Skeet's EduAsync blog series: msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx

This MSDN article also explains it: http://msdn.microsoft.com/en-us/library/vstudio/hh156513.aspx

Basically: a method modified by the async keyword contains at least one await expression or statement. The method runs synchronously until it reaches the first await expression, at which point it is suspended until the awaited task is complete. In the meantime, control is returned to the caller of the method. If the method does not contain an await expression or statement, then it executes synchronously.

Finally, this MSDN article: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx walks through a step-by-step example, about 1/3 of the way down the page:

like image 36
CodingWithSpike Avatar answered Oct 24 '22 17:10

CodingWithSpike