【问题标题】:Using async in ASP.Net MVC在 ASP.Net MVC 中使用异步
【发布时间】:2013-11-01 21:50:21
【问题描述】:

我有以下操作挂起并且从未返回:

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 的结果,那么为什么我没有得到一个没有任何内容的视图。

所以在我看来,它既没有等待返回:

UserManager.FindByIdAsync(User.Identity.GetUserId());

既没有返回空配置文件,也没有引发异常。所以当它在第一个例子中挂起时,我不明白这里发生了什么。

【问题讨论】:

  • 你的第一个代码 sn-p 没有编译。
  • 第二个代码 sn-p 没有错误,问题很可能与我们没有代码的 UserManager.FindByIdAsync 方法有关。如果我猜我会说它没有启动它返回的任务,因此该任务被无限期地等待。按照惯例,异步方法应始终启动它返回的任务。

标签: c# asp.net-mvc async-await


【解决方案1】:

我假设您的第一个示例是使用Result,因此是causing a deadlock that I explain on my blog

总之,ASP.NET 提供了一个“请求上下文”,它一次只允许一个线程进入。当您使用Result 阻止线程时,该线程被锁定在该上下文中。稍后,当FindByIdAsync 尝试在该上下文中恢复时,它无法恢复,因为其中已经阻塞了另一个线程。

【讨论】:

  • 感谢您的博文。正是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多