c# - 使用 ExecuteReaderAsync 时出现死锁

标签 c# .net-4.5 deadlock async-await c#-5.0

我正在尝试使用异步模式来执行 SQL 命令并返回 DataTable。 有人可以建议如何解决这个问题吗?

这是我的代码:

    private static async Task<DataTable> ExecuteAsync(Connections connection, SqlBuilder sql)
    {
        using (SqlConnection conn = new SqlConnection(GetConnectstring(connection)))
        {
            await conn.OpenAsync();
            using (SqlCommand cmd = new SqlCommand(sql.Query, conn))
            {
                foreach (var parameter in sql.ColumnValues.Where(d => !d.Name.StartsWith("#")))
                {
                    cmd.Parameters.AddWithValue(parameter.Name, parameter.Value);
                }

                //Why am I getting a deadlock when executing the next line?
                using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    return dt;
                }
            }
        }
    }

最好的问候, 托马斯

最佳答案

我怀疑您正在使用 WaitResult 进一步调用堆栈。这causes a deadlock如果从 UI 线程调用,如我在博客中所述。

关于c# - 使用 ExecuteReaderAsync 时出现死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18396985/

相关文章:

c# - 在 NUnit 2.5.8 中使用 TestContext 时出现 NullReferenceException

c# - C#中如何派生两个抽象类

c# - Task<WebResponse>.Wait 永远持续

.net - 如何在 MVC4 的 APIController 中使用我自己的依赖解析器

c# - 同时运行这两个语句时如何防止 EntityFramework 死锁

c# - 此正则表达式替换如何反转字符串?

c# - Asp.net的AutoEventWireup和反射?

c# - Await 运算符只能在 Async 方法中使用

mysql - InnoDB什么时候超时而不是报死锁?

go - 这是死锁吗?为什么执行程序说是死锁?