Yehia A.Salam
Yehia A.Salam

Reputation: 2078

Await and Async in same line

I understand how async works and how it compares with the javascript promises, but im not sure how a line like the below could have any benefit

IdentityResult result = await UserManager.CreateAsync(user, model.password);

since we're creating an async call and immediately waiting on the thread so the lines that follows won't be executed till the Async call calls complete.

Upvotes: 3

Views: 2540

Answers (2)

Harald Coppoolse
Harald Coppoolse

Reputation: 30464

Let's suppose you have a user interface, and your function UserManager.CreateAsync is called whenever a button is pressed.

I don't know the CreateAsync function, but since it is Async and awaitable I guess that the designer thought it would take long enough to be performed async.

If CreateAsync would take a minute and it wasn't awaitable, then your user interface would be dead for a minute.

Using this method your interface would still be responsive. If you used a CancellationToken as parameter in CreateAsync the user interface could even decide to cancel the task for instance to close down the program.

Upvotes: 1

i3arnon
i3arnon

Reputation: 116548

The benefit is that if that operation is truly asynchronous then at some point the calling thread will be freed to do other work in your application instead of being blocked synchronously.

That kind of usage brings higher scalability.

You're still waiting until the operation completes before moving on. Async methods don't magically run faster, but they do potentially use less resources and you can usually run multiple ones concurrently.

If we imagine that CreateAsync looks like this:

async Task<IdentityResult> CreateAsync()
{
    // do something
    await Task.Delay(1000);
    // do something else
}

Then at await Task.Delay(1000) you free up a thread and wait asynchronously instead of holding on to it for a second. That thread can execute other CPU operations in your process and avoid a context switch.

If CreateAsync is implemented right then there is some actual asynchronous operation instead of that Task.Delay

Upvotes: 5

Related Questions