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

What is Difference between 'public async Task<IActionResult>' and 'public ActionResult' in MVC

我不知道 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);
}

[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();
}

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

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

话虽如此,如果您不在 action 方法中使用异步编程,我相信它没有任何区别。但是,如果您使用 EF 或任何物有所值的库,它将是异步的。

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

就性能而言,您不会真正在开发上看到任何大的变化,但在生产或负载测试中您会看到收益。

总而言之,如果您看到异步实现,请使用它,除非您真的必须为特殊目的使用同步。