C # wait / asynchronously in WebApi, what's the point?

Does anyone know what the purpose of this is?

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); } 

Having studied this, he says that he runs the private method asynchronously, but synchronously waits for it to complete. My question is, does that make sense? Or is it just a bizarre but useless technique? I came across this while learning some code for Web API / MVC / SPA.

In any case, any ideas would be helpful.

+6
source share
1 answer

Despite its name, await does not actually work like Thread.Join. async and await are Microsoft's implementation of coroutines implemented using a continuation transition style. Work is reordered, so processing can continue while Task<T> is running. The compiler reinstalls the instructions to make the most of the asynchronous operation.

This article explains this as follows:

the wait expression does not block the thread on which it is running. Instead, it forces the compiler to sign the rest of the asynchronous method as a continuation of the expected task. The control then returns to the caller of the async method. When the task completes, it invokes its continuation, and the async method resumes where it left off.

For some simple code examples, await doesn't really make much sense, because there is no other work that you can do at the same time while you wait.

+8
source

Source: https://habr.com/ru/post/974957/


All Articles