In the new Identity template code, the controller code that signs in a user is wrapped in an async
block:
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationManager.SignIn(new AuthenticationProperties()
{ IsPersistent = isPersistent },
await user.GenerateUserIdentityAsync(UserManager));
}
But all of the calls to SignInAsync simply await
the task completion. So what's the point of the additional overhead and complexity of making the sign-in code asynchronous? Or is that a mystery left to the minds of the folks who created the template who may have envisioned some sort of asynchronous sign-in scenario?
EDIT: Ok, there seems to be a bit of confusion as to what I'm asking. Let's try this:
Why create an asynchronous SignInAsync function when all of the calls to the function are effectively synchronous:
await SignInAsync()
The async function would make sense if the caller did some other work before await
ing, but that's not the case...
Why create an asynchronous SignInAsync function when all of the calls to the function are effectively synchronous
You say this, but then give an example of an asynchronous call.
So, I think the confusion is around the difference between synchronous and sequential. Consider the code in question:
await SignInAsync();
This is an asynchronous call. The method it's in will be evaluated sequentially because it immediately await
s the returned task, but that does not make it synchronous. It's still asynchronous.
You can think of "sequential" as "one step at a time"; this is in contrast to "concurrent", which does multiple things at a time. "Asynchronous" can mean "doing some operation without blocking", whereas "synchronous" means "using the calling thread for the duration of the operation".
Async and await enable asynchronous sequential code (and also asynchronous concurrent code, if you use something like Task.WhenAll
).
I would guess that GenerateUserIdentityAsync
is async
because the synchronous variant blocks waiting for IO. This is especially bad on the server as while the thread is blocked it could be serving another request. Asynchronous code on the server improves scalability. On the client, it improves UI/Website responsiveness.
When you await
something, the generated state machine returns immediately after kicking off the operation and then executes the remainder of the method on the same SyncrhonizationContext
after the asynchronous operation completes. So all you are avoiding is having your thread blocked by some IO operation.
This additional complexity is well worth it, it will make your client more responsive and your server more scalable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With