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?
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:
.Wait() or .Result (or similar) at all - instead, only use await and make it a properly async actionor, 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
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:
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.
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