Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbConnection.Open() works but dbConnection.OpenAsync() doesn't

This is a tough one. Using the exact same query string, the exact same following code:

using (var db = new SqlConnection(queryString))
{
   await db.OpenAsync();
   var results = await db.ExecuteSomethingAsync...;
   db.Close();
{

Will work when ran from a windows application. It will however get stuck forever in await OpenAsync() when ran from IIS Express or IIS 7. If I replace that line with db.Open() it works though. Any suggestions?

like image 660
Luis Ferrao Avatar asked Dec 05 '25 10:12

Luis Ferrao


2 Answers

await needs to be treated with caution in ASP.NET, because of how the sync-context wants to serialize the work for a single request. The code you post is probably fine by itself - the await isn't going to block. However, I expect that somewhere in the call chain for this, you are calling .Wait() or accessing .Result, rather than await.

There are a few options here:

  • don't use .Wait() or .Result (or similar) at all - instead, only use await and make it a properly async action
  • or, use .ConfigureAwait(false) to tell it to ignore sync-context; unfortunately, this would need to be added to all the places that you await, i.e.

    await db.OpenAsync().ConfigureAwait(false);
    var results = await db.ExecuteSomethingAsync(...).ConfigureAwait(false);
    
  • or, just use sync code - in most cases the sql is going to run very quickly - so pushing it async is not necessarily helping as much as you might think; obviously this may vary between usage; but a key point to keep in mind here is that ASP.NET is already inherently threaded - it isn't as though the entire server grinds to a halt here

like image 106
Marc Gravell Avatar answered Dec 06 '25 23:12

Marc Gravell


As others have mentioned, first ensure you have no Wait or Result calls up your hierarchy. A chain of async methods ends at an entry point that depends on the framework. In a UI/WebForms app, this is usually an async void event handler. In a WebAPI/MVC app, this is usually an async action.

Two other things to check for ASP.NET are:

  • Ensure your target platform is .NET 4.5.
  • Ensure you have UseTaskFriendlySynchronizationContext set to true.

If you need to support async in a shared library on multiple platforms, you may find the Microsoft.Bcl.Async NuGet library to be helpful.

like image 22
Stephen Cleary Avatar answered Dec 07 '25 00:12

Stephen Cleary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!