c# - 在 ASP.Net MVC 中使用异步

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

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

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/

相关文章:

c# - 如何在路径段中包含数字(散列)字符#?

c# - restsharp 发出多个异步请求

c# - VS 在 C# 代码中获取返回值?

c# - 将 URL 转换为 Controller / Action 对

asp.net-mvc - Autofac:有什么方法可以解决最里面的范围吗?

c# - 将 native 移动开发与 Xamarin 相结合

asp.net-mvc - 谷歌正在索引帖子操作

python - 将 asyncio.Queue 用于生产者-消费者流程

javascript - 如何通过管理 Promise(异步和等待)来绕过 5000ms 的 jest setTimeout 错误

c# - 取消不接受 CancellationToken 的异步操作的正确方法是什么?