gpt4 book ai didi

asp.net-core-1.0 - MVC中 'public async Task'和 'public ActionResult'有什么区别

转载 作者:行者123 更新时间:2023-12-01 23:17:10 24 4
gpt4 key购买 nike

我不知道 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 代码现在有 async 但有什么区别。一个比另一个提供更好的性能吗?用一个比另一个更容易调试问题吗?我应该为我的应用程序更改其他 Controller 以添加 Async 吗?

最佳答案

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

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

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

在性能方面,您不会真正看到 Dev 上的任何重大变化,但在生产或负载测试中,您会看到 yield 。

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

关于asp.net-core-1.0 - MVC中 'public async Task<IActionResult>'和 'public ActionResult'有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com