3

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.

Yehia A.Salam
  • 1,987
  • 7
  • 44
  • 93
  • It depends on how the operation is implemented, but if it's implemented correctly it will free the thread at some point waiting for async operation (e.g. IO or network access) to complete. – MarcinJuraszek Jul 26 '15 at 18:21
  • 1
    *immediately waiting on the thread* - `await` doesn't make the *thread* wait, it makes the rest of the method wait. That's the whole point! – Ant P Jul 26 '15 at 18:24

2 Answers2

5

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

i3arnon
  • 113,022
  • 33
  • 324
  • 344
1

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.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116