我不知道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吗?
仅返回ActionResult的action方法本质上是同步的。因此,在MVC操作中执行的任何长时间运行的方法都将保留该线程,而不使其可用于服务其他Web请求。但是,当您使用async Task<ActionResult>
并在长时间运行且异步的操作中调用方法时,线程将被释放,并且当长时间运行的方法返回时,将启动回调来接管。
话虽如此,如果您不在action方法内使用异步编程,我相信它不会有任何不同。但是,如果使用EF或任何值得其使用的库,它将是异步的。
作为开发人员,除了调用和等待异步方法外,您不需要做任何特别的事情,因此不使用它实际上没有任何价值。
在性能方面,您实际上不会在Dev上看到任何大的变化,但是在产品或负载测试中,您会看到收益。
概括地说,如果您看到异步实现,请使用它,除非您确实必须出于特殊目的使用同步。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句