asp.net-mvc-4 - 使用异步操作运行同步代码

标签 asp.net-mvc-4 async-await

我有一个搜索操作,它有两个路径,一个同步路径,仅返回一个简单 View ,另一个异步路径,异步执行搜索,然后返回一个 View 。两者都是 GET 请求,因此它们是同一操作的一部分。

问题是,当我访问操作“localhost:XXXX/Home/Search”时,页面会无限加载。使用 Fiddler,我可以看到请求永远不会返回。我已经对其进行了调试,并且它已到达最后一行代码,但是请求再次未完成。

我已将重现简化为以下内容:

public async Task<ActionResult> Search() 
{ 
    return View(); 
} 

VS11 警告我代码将在没有等待的情况下同步运行,这很好,但请求未完成。

这应该有效吗?或者我需要在这里做其他事情吗?

编辑

这是面向 .NET 4.5 的 MVC 4。

编辑2

对于那些在代码中看得更清楚的人,这就是为什么我需要在异步操作中进行同步:

public async Task<ActionResult> Search(string query = null)
{
    if (string.IsNullOrWhiteSpace(query))
        return View(new SearchViewModel());   // never loads

    var model = await _someService.SearchAsync(query);
    return View(model);    // loads
}

最佳答案

这是测试版中的一个已知错误。 To quote Stephen Toub:

The short answer is that there is a known bug in ASP.NET MVC in the .NET 4.5 Beta that results in this issue when the async method completes synchronously. Until a fix is available, a simple workaround is to add "await Task.Yield();" as the first line of the async method, forcing it to complete asynchronously. For this to work correctly, you also need to ensure you're using the new SynchronizationContext supplied by ASP.NET in .NET 4.5, which means ensuring you have the line:

<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />

in the appSettings section of your configuration file.

关于asp.net-mvc-4 - 使用异步操作运行同步代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627329/

相关文章:

javascript - 在 Release模式下运行 ASP.NET MVC 4 应用程序不会捆绑和缩小 js 文件

c# - 当全局注册操作过滤器时跳过特定操作的过滤器

asynchronous - 我怎样才能等待一个变量

asp.net-mvc-4 - droplink 的 sitecore mvc 值

c# - 提交后重定向到同一页面

javascript - Ajax 调用后从 Controller 重定向(包括参数)

javascript - AWS Lambda 和 promise : Callbacks not being called

c# - 如何等待 Func<Task<string>>?

javascript - 如果 promise 失败,捕获但做下一步

c# - 将项目转换为 .Net 4.5(使用 TPL)