Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlConnection.OpenAsync() hangs when there are no active connections

When I run this:

using(SqlConnection connection = new SqlConnection(connectionString)){
    await connection.OpenAsync();
}

It hangs on the connection.OpenAsync() line.

If I look in Sql Server Management Studio how many connections are active for the database, there's only one: probably the one that this code uses. So, I'm not sure it is that I'm running out of connections from the app pool.

What am I doing wrong?

like image 791
AxiomaticNexus Avatar asked Oct 17 '14 18:10

AxiomaticNexus


1 Answers

The problem was not the connection at all. The problem was that I shot myself in the foot with a deadlock on my threads. I was trying to make a synchronous call to the method containing the connection.OpenAsync(), like this:

Task task = MyAsyncMethod();
task.Wait();

By calling task.Wait() I was blocking the thread. When await connection.OpenAsync() returns, the rest of the method wants to run on the same thread I just blocked, so the task never finishes and task.Wait() never returns.

The solution:
Because in my async method I had nothing requiring me to stick to the same thread that called it, I simply used await connection.OpenAsync().ConfigureAwait(false), to make it run the remainder of the method in a different thread other than the one I block with task.Wait().

like image 177
AxiomaticNexus Avatar answered Sep 21 '22 15:09

AxiomaticNexus