I want to execute some queries async. But when I debug through the code, most times when an ToListAsync() is called the program stops. There is no visible exception, and the
From the comments:
It is a wpf application. The commands are within an async method. I call this from a non-async method using
var result = LoadAsync.Result();
Right there, thats a deadlock. The DispatcherSynchronizationContext tries to marshal the continuation (everything after the first await
) back onto the dispatcher (UI) thread, which is currently blocked by the call to LoadAsync.Result
The solution:
await
at the top of your call stack by making your method return an async Task
instead of using Task.Result
:
await LoadAsync();
If you absolutely cant change the method at the top of of the stack to async Task
and for some obscure reason have to still call Task.Result
, use ConfigureAwait(false) when awating your inner async methods. This will tell the sync context to explicitly not attempt to marshal work back to the dispatcher thread:
var res1 = await context.Address().Where(...).ToListAsync().ConfigureAwait(false);
var res2 = await context.Person().Where(...).ToListAsync().ConfigureAwait(false);
var res3 = await context.Rule().Where(...).ToListAsync().ConfigureAwait(false);