thomas
thomas

Reputation: 1453

Getting deadlock when using ExecuteReaderAsync

I'm trying to use the async pattern to execute a SQL command and return a DataTable. Can someone please advice how to solve this problem?

This is my code:

    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;
                }
            }
        }
    }

Best regards, Thomas

Upvotes: 2

Views: 4105

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456507

I suspect you are using Wait or Result further up your call stack. This causes a deadlock if called from a UI thread, as I describe on my blog.

Upvotes: 11

Related Questions