Reputation: 14417
So, I'm just catching up on the old MVC 5 stuff now that I'm out of university.
I just looked at this implementation, its point 3. about registering a user, i noticed it used async
:
[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);
}
I just want a bit of clarity, I am familiar with the async
keyword and its association with Task
and await
, do you have to use this with Ajax
operations?
Can it be used with Ajax
operations?
If so, I guess Ajax
would be the best way to achieve it.
Upvotes: 1
Views: 1316
Reputation: 25221
Do you have to use this with Ajax operations?
No, absolutely not. You can use synchronous code with AJAX operations (and most of the time you probably will): the client (browser) request is still asynchronous even if a server thread is blocked in the background.
Can it be used with Ajax operations?
Yes, it can. When it's appropriate. Generally to allow long-running I/O operations to complete without blocking worker threads.
In your example, the Register
method will be waiting for UserManager.CreateAsync
to complete but - in the meantime - the thread executing this method is free to handle other requests.
Here's some good documentation.
Upvotes: 2
Reputation: 34822
Web code is almost always asyncronous out of the box. This is due to IIS hosting numerous threads in a pool, all listening for connections. As a result your code can run on multiple threads concurrently. async
and await
are a means of delegating work to a different thread pool and receiving the response when the work is done. It has nothing to do with the native-async ASP.NET pipeline, but can be used within the pipeline for additional performance gains. Reading this might help clear it up for you.
Upvotes: 1