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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With