Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# await / async in WebApi, what's the point?

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.

like image 329
beautifulcoder Avatar asked Sep 08 '14 01:09

beautifulcoder


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

How old is the letter C?

The letter c was applied by French orthographists in the 12th century to represent the sound ts in English, and this sound developed into the simpler sibilant s.


1 Answers

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.

like image 113
Robert Harvey Avatar answered Sep 28 '22 06:09

Robert Harvey