简体   繁体   中英

What are the consequences of marking a method async in C# 5.0?

From what I understand in order to use await I have to be inside of a method which is marked as async . If that's the case, I can use await on any Task<Thing> to somewhat synchronously retrieve the value of the Task 's result.

Task<bool> task = new Task<bool>(() => false);
task.Start();

int result = await task;

To do this I need to be inside of a method marked with async .

What I want to ask here is what exactly is the meaning of async and what are the consequences of marking a method with async .

Also, what's the difference between these two?

Task<bool> Foo() {
  var task = new Task<bool>(() => false);
  task.Start();
  return task;
}

async Task<bool> Foo2() {
  var task = new Task<bool>(() => false);
  task.Start();
  return await task;
}

I can both use them with await from inside an async method.

var res1 = await Foo();
var res2 = await Foo2();

Is the only difference that Foo2 can use await in it's body, while Foo can't?

It just alerts the compiler that the method may contain await expressions. Which enables it to do a consistency check on the method return value. And enables the rewriting logic built into the compiler that makes it transform the method into a hidden class.

If you don't actually use the await operator in the method body then this rewriting doesn't need to occur and the async keyword isn't needed either. If you use async anyway then you'll get an otherwise benign warning (CS1998) to point out that your code is probably not what you intended to write. A good diagnostic.

The main purpose of the async keyword is to avoid conflicts with code used in prior to C# 5.0 In other words we could say to maintain backword compatiblity.

Prior to C# 5.0 you could have used identifiers/types as await

void Somemethod()
{
    int await = 5;//identifier
    await myAwait = new await();//type
}

Above code is completely valid in prior to C# 5.0(in C# 5.0 also this is valid unless and until you use it in async method), What happens if await is added as a reserved keyword in c# 5.0? Your code won't compile. and that would be a breaking change.

So to maintain backward compatiblity language designers chosen to make await as a contextual keyword. So next question arises await is going to be a contextual keyword but what is the context here?

Well, there comes the async keyword, presence of async just enables the await keyword. and it makes the compiler to emit AsyncStateMachineAttribute to the method as well.

I didn't talk anything about how async method is transformed assuming you know that already or that is beyond the point of the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM