In C #, what is the key word await?

30

I was studying this documentation on Asp.net Identity , and the examples in C # have a keyword that I do not know, which is 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 is this keyword for?

    
asked by Guilherme de Jesus Santos 29.01.2014 в 17:36
source

7 answers

23

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

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

The await keyword is used to wait until a function (which usually takes a while to execute completely) returns its result - and it waits for that result without blocking the program flow.

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

    
answered by 29.01.2014 / 17:42
source
27

What is

What await is a "command" for the code to be waiting for completing a task and continue other executions can happen concomitantly , everyone has already said. I'll give you some extra details.

A await can only be used in a method declared with the async modifier. The compiler needs to know in advance that this method will need a state machine that allows the concomitant execution of the code to expect and other code streams in your application. Then this code runs asynchronously.

State Machine

The await indicates at which point the code will undergo the spin-off and the state machine created internally in your application (you do not need to know about it) interleaving the execution of the two execution fronts . At this point, it's as if the code suffers a waxing of the method there with a return , more precisely a yield return , and returns control of the code to its calling method doing what it has to do normally. In the meantime the code that comes next to await that is on the same line, even statement , continues to run concomitantly (in parallel or not). The remainder of the code below await will also run after the normal completion of the waiting task as if the execution had never left.

To understand how the state machine works, let's look at a code demonstrated by Microsoft :

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

Tasks

It is important to note that methods that ends with an integer result.

Task void

You can actually return nothing (% w / o%) too, both if it's an action to run. If the code returns nothing it can be executed asynchronously but it can not resume from there, 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.

Name convention

This is not mandatory but it is agreed that the method terminates with the word void to better indicate that it is an appropriate, prepared method for asynchronous execution.

Threads

A common mess is to imagine that Async creates new threads . This is not true, await is just a program flow control such as await or while . Of course it is more complicated, but it does nothing more than this. If the ( return ) tasks involved need a new thread to perform better, this is a problem for the Task class to solve. And this type exists precisely to abstract the raw processing of the 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 the recommended threshold for deciding whether something should be asynchronous or not);
  • Your application is free to do whatever else it needs to do without waiting for this creation to run out.
  • When it is finished, the stream will be redirected to your code again and continue execution;
  • so it will check if the operation was successful, if it was going to sign-in asynchronously, that is, it will release the application again to do other things and
  • At the end it returns something;
  • If it was not successful, it will add the errors synchronously, that is, it will leave your application waiting (no problem, it can be a quick operation);
  • finally will return something.
answered by 04.06.2014 в 18:43
16

What await means

The await keyword is used to make asynchronous calls, so if the method being called is delayed, everything 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 your internal implementation is delayed, it will stop, leaving código-parte-2 on hold, waiting to be executed after the completion of the internal processing of the called function using await .

And in the context of MVC?

An MVC action that is defined with async , allows a method within it to be called with await , causing the MVC not to occupy the queue of requests that are processed by the server, until the called method with await complete, and finally return a result.

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

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

References

MSDN: Using an asynchronous controller in ASP.NET MVC

In this MSDN topic, it has a very explanatory picture of what happens, basically everything that comes after the call using await in the asynchronous action, is transferred to another thread, other than the pool that answers requests, therefore, free to attend other requests.

This blog , in English , explains exactly the asynchronous actions calls, using async and why their use causes the server to be able to serve more requests simultaneously.

    
answered by 29.01.2014 в 18:24
6

First of all, I recommend reading Stephen Cleary's blog: link

Put simply:

From .NET 4.0, you can encapsulate a task (which can run in another thread asynchronously or not) in a class Task or Task<T> .

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

  • (If the Task is not completed) The current thread is free to perform other tasks until the Task completes. As soon as it is complete, the result IdentityResult will be placed in the result variable.
  • (If the Task has already completed) the result IdentityResult is placed in the variable result .
  • answered by 29.01.2014 в 17:43
    1

    According to the official documentation , this keyword suspends execution of a method called asynchronously, until a certain task is completed. The text on the link is more in-depth. You can also the link to the Portuguese translation .

        
    answered by 29.01.2014 в 17:40
    0

    By this MSDN article , and by my understanding, await is for the method, which contains an asynchronous task, waits at the end of the task execution and finishes executing its code.

        
    answered by 29.01.2014 в 17:39
    0

    The word await is a new syntax for the use of 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. link

        
    answered by 29.01.2014 в 17:42