Open
Description
Eventually we run into a scenario, where we cannot go async/await for the full call stack. It's unclear what to do in such case, please help by extending this documentation.
What we run into:
- We need to call a method that returns a
Task
orTask<T>
, but we cannot use await keyword. The code cannot be changed to accommodate async/await. - At worst, the request starts with an async/await method, but calls synchronized functions and they call async/await methods again, all in the same stack.
- There are number of options, all of which are prone to deadlocks and their use is discouraged.
Wait()
blocks and deadlocks. Exceptions are ugly.GetAwaiter().GetResult()
is better for exceptions, but still blocks.RunSynchronously()
is for special uses only.ConfigureAwait(false)
requires await and also all decendant awaits need to callConfigureAwait(false)
, not acceptable.
- Nonetheless, we still need to somehow wait for the task and get a result.
- Do we need to use something like
var result = Task.Run(async () => await task).GetAwaiter().GetResult();
- Do we need to use something like
The internet is not helpful in giving a silver bullet. We need working code, not fancy theories.
Document Details
⚠ Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.
- ID: d885f1eb-2b37-693b-c91f-74b748c9424a
- Version Independent ID: 77bdee53-c2a0-e16f-c93a-3ca0afae0b93
- Content: Asynchronous programming - C#
- Content Source: docs/csharp/asynchronous-programming/async-scenarios.md
- Product: dotnet-csharp
- Technology: csharp-async
- GitHub Login: @BillWagner
- Microsoft Alias: wiwagn