【问题标题】:ASP.NET MVC 4 asyncronous database call: never returns the HTTP responseASP.NET MVC 4 异步数据库调用:从不返回 HTTP 响应
【发布时间】:2012-04-16 13:07:51
【问题描述】:

我尝试对 SQL Server 进行异步数据库调用并将其与新的 ASP.NET MVC 4 异步功能一起使用,但奇怪的是它根本没有返回。我调试了代码,运行良好,但不知何故 HTTP 请求永远挂起。

这是我所做的:

这是数据库调用方法:

public async Task<IEnumerable<Car>> GetCarsAsync() {

    var connectionString = ConfigurationManager.ConnectionStrings["CarGalleryConnStr"].ConnectionString;
    var asyncConnectionString = new SqlConnectionStringBuilder(connectionString) {
        AsynchronousProcessing = true
    }.ToString();

    using (var conn = new SqlConnection(asyncConnectionString)) {
        using (var cmd = new SqlCommand()) {

            cmd.Connection = conn;
            cmd.CommandText = selectStatement;
            cmd.CommandType = CommandType.Text;

            conn.Open();

            using (var reader = await cmd.ExecuteReaderAsync()) {

                return reader.Select(r => carBuilder(r)).ToList();
            }
        }
    }
}

这里,SqlDataReader 上的 Select 方法是我实现的扩展方法。 carBuilder 私有方法只是返回一个 Car 类的实例。

这是控制器类:

public class HomeController : Controller {

    private readonly GalleryContext ctx = new GalleryContext();

    public async Task<ViewResult> IndexAsync() {

        return View("Index", await ctx.GetCarsAsync());
    }
}

知道我错过了什么吗?

【问题讨论】:

标签: asp.net sql-server asp.net-mvc asp.net-mvc-4 async-await


【解决方案1】:

MVC 4 Beta 中存在一个错误,当您返回一个很快完成的异步 Task 时会导致挂起。

解决方法是将以下内容添加为您的操作方法的第一行:

await Task.Yield();

你能看看这是否能解决问题吗?

更多信息在这里:http://aspnetwebstack.codeplex.com/workitem/22

【讨论】:

    【解决方案2】:

    您的控制器仍然需要从AsyncController 派生(请参阅Exercise 4: Using Asynchronous Controllers),但现在您需要编写更少的代码来实现与Task&lt;T&gt; 相同的结果。

    所以这应该有效:

    public class HomeController : AsyncController {
    
        private readonly GalleryContext ctx = new GalleryContext();
    
        public async Task<ViewResult> IndexAsync() {
    
            return View("Index", await ctx.GetCarsAsync());
        }
    }
    

    【讨论】:

    • 我认为没有必要。我还有其他几个基于任务的异步操作,它们异步使用 Web 服务,以及从 Controller 类派生的控制器。不过让我试试。
    • 啊,真糟糕!它起作用了,但很奇怪,因为正如我所说,我还有其他几个基于任务的异步操作,它们异步使用 Web 服务以及从 Controller 类派生的控制器。
    • 我不知道是什么导致了差异...但是根据示例和网上其他文章,您应该源自AsyncController
    • 嗨,请参阅@marcind 的回答。这就是解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 2022-01-19
    相关资源
    最近更新 更多