In C#, what is the await keyword for?

Asked

Viewed 9,251 times

29

I was studying this documentation about Asp.net Identity, and in the examples in C# has a keyword that I don’t know, which is the await, example :

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
} 

What’s that keyword for?

7 answers

33

What is

Who await is a "command" for the code to be awaiting by the conclusion of a task and carry on normal execution allowing other executions to happen concomitantly, everyone already said. I’ll give some extra details.

A await can only be used in a method declared with the modifier async. The compiler needs to know beforehand that that method will need a state machine enabling the concurrent execution of the code to be expected and other code flows in its application. Then this code runs asynchronously.

State machine

The await indicates at which point the code will be split and the state machine built internally in your application (you don’t need to know about it) you will have to stay interleaving the execution of the two fronts of implementation. At this point, it’s as if the code has been waxed by the method there with a return, more precisely a yield return and return control of the code for its calling method to do what it has to do normally. Meanwhile the code that comes next to the await that is on the same line, even statement, continues to run concurrently (parallel or not). The rest of the code below the await will also be executed after normal completion of the task on hold as if the execution had never left there.

To understand the functioning of the state machine we see a code demonstrated by Microsoft:

async

Since the code uses a state machine, it uses a continuation which is provided by yield return infiltrated in your code by the compiler.

Tasks

It is important to note that codes (methods or Amble) which will be implemented by await must must return a Task, or a derivative of it, since it will perform a... task.

If you need to return a result, a int for example, the method/lambda call needs to take your kind return Task<int>, since it is a operation ending with an entire result.

Task void

In fact it can return nothing (void) also, both if they are one action to be executed. If the code returns nothing it can be executed asynchronously but it cannot resume from then on, that is, it is useless to put anything to be executed after the execution of the asynchronous code. Rarely is this necessary. In an event it is a good use since it has to return nothing.

Naming convention

It is not mandatory but it is agreed that the method ends with the word Async to better indicate that it is an appropriate, prepared method for asynchronous execution.

Threads

A common confusion is to imagine that the await creates new threads. This is not true, the await is just a program flow control as is the while or the return. Of course it is more complicated, but does nothing beyond this. If the tasks (Task) involved need a new thread to better execute, this is a problem for the class Task resolve. And this type exists precisely to abstract the raw treatment of threads allowing a better understanding and work of the programmer.

Your example

  • While the application is creating a user, it will potentially take more than 50ms (this is recommended limit to decide whether something should be asynchronous or not);
  • your application is free to do what else it needs to do without waiting for this creation to end.
  • When it is over, the flow will be diverted to your code again and will continue the execution;
  • so it will check if the operation was successful, if it is going to do the Sign-in asynchronously, ie, will release the application again to do other things and;
  • at its end returns something;
  • if it was unsuccessful, will add the errors synchronously, ie, will leave your application waiting (no problem, can be a quick operation) and;
  • will finally return something.
  • 2

    The best explanation for asynchronous methods

  • It would only be used in I/O method?

  • 1

    @Danover is usually the most suitable, it is difficult to find a situation that is useful and does not have IO.

26


The keywords async and await are used for asynchronous programming. For reference, see: Asynchronous programming with Async and Await.

In essence, you use the keyword async in the declaration of a function that depends on the keyword await. This is due to the fact that when using the await, your program must "wait" for a result, and as "wait" is a waste of time, it "waits" asynchronously (in the background).

The keyword await is used to wait until a function (which usually takes a long time to run completely) returns its output -- and it waits for this result without blocking the program flow.

The keyword await should be used to receive the result of a Task.

  • 1

    The mentioned article contains a diagram that helped me a lot to visualize the asynchronous process.

17

What does await mean

The keyword await serves to make asynchronous calls, so that if the method being called is slow, all that comes after the call using await is suspended, waiting to be executed in a queue.

For example:

código parte 1;
await FazerAlgoQuePodeDemorar();
código parte 2;

If the function called FazerAlgoQuePodeDemorar in its internal implementation will take time, it will interrupt itself, leaving the código-parte-2 suspended, waiting to be executed after the completion of the internal processing of the called function using await.

And in the context of the MVC?

A MVC action that is defined as async, allows a method within it to be called with await, causing MVC to not occupy the request queue that is processed by the server until the method called with await finish, and finally return a result.

This was done because each time a non-synchronistic action is called, it occupies a thread that is available to process requests, and there is a limit to the number of threads that do this work. Using async, request processing thread is released to process other requests, while a call made with await takes care of the request processing done previously in another plan.

This is only really useful, for actions that make I/O calls, such as database access, requests to external servers, hard drive recordings, and other tasks that can be done asynchronously.

References

MSDN: Using an asynchronous controller in ASP.NET MVC

In this topic of MSDN, has a very explanatory image of what happens, basically everything that comes after the call using await in the asynchronous action, it is transferred to another thread, other than the one of the pool that meets requests, thus leaving it free to meet other requests.

Imagem da MSDN mostrando as threads A) do pool que atende requests B) outra thread

This blog, in English, explains exactly the asynchronous action calls, using async and why its use makes the server capable of meeting more requests simultaneously.

7

First of all, I recommend reading this blog (in English) by Stephen Cleary: http://blog.stephencleary.com/2012/02/async-and-await.html

Put in a simple way:

From . NET 4.0, it is possible to encapsulate a task (which can run in another thread asynchronous or not) in a class Task or Task<T>.

In this case, the method CreateAsync returns a Task<IdentityResult> which, at that point, may be completed or not. A keyword await causes:

  1. (If the Task is not completed) A thread stay free to perform other tasks until the Task is completed. Once completed, the result IdentityResult will be placed in the variable result.
  2. (If the Task has already completed) the result IdentityResult is placed in the variable result.

1

0

For this article by MSDN, and by my understanding, the await serves for the method, which contains an asynchronous task, wait for the end of the task execution and finish executing your code.

0

The word await is a new syntax for using asynchronous methods. It should be placed before each asynchronous method and the method where we are should always have the async identifier before the type we have to return.

These methods should always return void or Task. For more information see the following link. http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.