SqlConnection.OpenAsync() hangs when there are no active connections
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()
.
Another reason it could hang is because the implementation is bad. OpenAsync(CancellationToken)
doesn't even use the cancellation token for the Open operation, so you can't actually cancel it. You have to wait for it to timeout. All it does is return a cancelled task if the cancellationToken was already set when you called the method, something you could check yourself without any special implementation. So this "async" overload is actually useless.