MVC中的'public async Task <IActionResult>'和'public ActionResult'之间有什么区别

Pra*_*han 3 asp.net-core-1.0

我不知道Asp.Net Core MVC6中这两种方法之间的区别是什么

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPost(int? id)
{
    if (id == null)
    {
        return NotFound();
    }
    var studentToUpdate = await _context.Students.SingleOrDefaultAsync(s => s.ID == id);
    if (await TryUpdateModelAsync<Student>(
        studentToUpdate,
        "",
        s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate))
    {
        try
        {
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        catch (DbUpdateException /* ex */)
        {
            //Log the error (uncomment ex variable name and write a log.)
            ModelState.AddModelError("", "Unable to save changes. " +
                "Try again, and if the problem persists, " +
                "see your system administrator.");
        }
    }
    return View(studentToUpdate);
}
Run Code Online (Sandbox Code Playgroud)

[HttpPost, ActionName("Edit")]
[ValidateAntiForgeryToken]
public ActionResult EditPost(int? id)
{
    if (id == null)
    {
        return NotFound();
    }
    var studentToUpdate =  _context.Students.SingleOrDefaultAsync(s => s.ID == id);
    if (TryUpdateModelAsync<Student>(
        studentToUpdate,
        "",
        s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate))
    {
        try
        {
            _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        catch (DbUpdateException /* ex */)
        {
            //Log the error (uncomment ex variable name and write a log.)
            ModelState.AddModelError("", "Unable to save changes. " +
                "Try again, and if the problem persists, " +
                "see your system administrator.");
        }
    }
    return View();
}
Run Code Online (Sandbox Code Playgroud)

我看到MVC代码现在具有异步功能了,但有什么区别。一个是否比另一个具有更好的性能?调试一个问题是否比另一个容易?我应该为我的应用程序更改其他控制器以添加Async吗?

Muq*_*han 6

仅返回ActionResult的action方法本质上是同步的。因此,在MVC动作中执行的任何长时间运行的方法都将保留该线程,而不使其可用于服务其他Web请求。但是,当您使用async Task<ActionResult>并在长时间运行且异步的操作中调用方法时,线程将被释放,并且当长时间运行的方法返回时,将启动回调来接管。

话虽如此,如果您不在动作方法中使用异步编程,我相信它不会有任何不同。但是,如果您使用EF或值得其使用的任何库,它将是异步的。

作为开发人员,除了调用和等待异步方法外,您不需要做任何特别的事情,因此不使用它实际上没有任何价值。

在性能方面,您实际上不会在Dev上看到大的变化,但是在产品或负载测试中,您会看到收益。

总结一下,如果您看到异步实现,请使用它,除非您确实必须出于特殊目的使用同步。