问题
Does anybody know what is the purpose of doing this?
private async Task<bool> StoreAsync(TriviaAnswer answer) { ... }
[ResponseType(typeof(TriviaAnswer))]
public async Task<IHttpActionResult> Post(TriviaAnswer answer)
{
var isCorrect = await StoreAsync(answer);
return Ok<bool>(isCorrect);
}
From examining this, it is telling it to run the private method asynchronously but synchronously wait for it to end. My question is, is there any point to this? Or is this just a fancy yet futile technique? I ran into this while studying some code for Web API / MVC / SPA.
Anyway, any insights would be useful.
回答1:
Despite its name, await doesn't actually work like Thread.Join. async and await are Microsoft's implementation of coroutines, implemented using a Continuation Passing Style. Work is reordered so that processing can continue while the Task<T> is being completed. Instructions are re-arranged by the compiler to make maximum use of the asynchronous operation.
This article explains it thusly:
An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.
For some trivial code examples, await doesn't really make much sense, because there is no other work that you can do in the meantime while you are awaiting.
来源:https://stackoverflow.com/questions/25716366/c-sharp-await-async-in-webapi-whats-the-point