(The title looks similar to SqlConnection.Open vs SqlConnection.OpenAsync - what's different between the two beyond the obvious? but a. It doesn't has any answer, and b. the observations in my case are different)
While bench-marking to chase a performance issue in an asp.net service, I accidentally hit a queer observation where SqlConnection.Open
performs far better than SqlConnection.OpenAsync
(more details below).
From the source code here looks like the code of Open
is just a subset of OpenAsync
. Diff here
I am curious on given Open
does exactly same things as OpenAsync
, what is the advantage of using the async version(if any)?
Details:
This is how I create the connection
using (SqlConnection connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
// run actual operation on connection (in an async way)
}
This code block takes
13 seconds on an average for 100 concurrent calls
. I have tried increasing the thread pool count to 200 to reduce chances of tasks
waiting for threads. The observation doesn't change even after letting the default threadpool count.
The interesting part is if I change await connection.OpenAsync()
with connection.Open()
the performance improves 10 times.
1.01 seconds on an average of 100 concurrent calls
.
I tried playing around with connection pool settings
and looks like even if I reduce it to an arbitrarily low number (2 is what tested with) the number doesn't change much.
The driver code is:
Task.WhenAll(Enumerable.Range(0, maxConcurrentCalls).Select((idx) => CallQuery(idx))).Result;
The reason I do a wait (by doing a .Result
is because the driver code is a console app which has to have a sync main
). In the actual production code everything including the controller is async
.