ℙℕℤℝ 2014-05-29 16:12
浏览 29

ASP.NET任务等待Ajax

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.

  • 写回答

2条回答 默认 最新

  • 狐狸.fox 2014-05-29 16:20
    关注

    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.

    评论

报告相同问题?