我有以下挂起且从未返回的操作:
public Task<ActionResult> ManageProfile(ManageProfileMessageId? message)
{
ViewBag.StatusMessage =
message == ManageProfileMessageId.ChangeProfileSuccess
? "Your profile has been updated."
: message == ManageProfileMessageId.Error
? "An error has occurred."
: "";
ViewBag.ReturnUrl = Url.Action("ManageProfile");
var user = UserManager.FindByIdAsync(User.Identity.GetUserId());
var profileModel = new UserProfileViewModel
{
Email = user.Email,
City = user.City,
Country = user.Country
};
return View(profileModel);
}
但是当我把它转换成这个时:
public async Task<ActionResult> ManageProfile(ManageProfileMessageId? message)
{
ViewBag.StatusMessage =
message == ManageProfileMessageId.ChangeProfileSuccess
? "Your profile has been updated."
: message == ManageProfileMessageId.Error
? "An error has occurred."
: "";
ViewBag.ReturnUrl = Url.Action("ManageProfile");
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var profileModel = new UserProfileViewModel
{
Email = user.Email,
City = user.City,
Country = user.Country
};
return View(profileModel);
}
它马上就回来了。所以我不确定这是怎么回事?如果它像不等待 FindByIdAsync 的结果而返回的方法一样简单,那么为什么我没有得到一个什么都没有的 View 。
所以在我看来它既没有等待返回:
UserManager.FindByIdAsync(User.Identity.GetUserId());
既没有返回空配置文件也没有抛出异常。所以当它在第一个示例中挂起时,我不明白这里发生了什么。
最佳答案
我假设您的第一个示例使用的是 Result
,因此 causing a deadlock that I explain on my blog .
总之,ASP.NET 提供了一种“请求上下文”,一次只允许一个线程进入。当您使用 Result
阻塞线程时,该线程将被锁定到该上下文中。稍后,当 FindByIdAsync
尝试在该上下文中恢复时,它无法恢复,因为其中已经有另一个线程被阻塞。
关于c# - 在 ASP.Net MVC 中使用异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19695152/