Skip to content

How to wait Tasks when unable to await? #37040

Open
@seppo498573908457

Description

@seppo498573908457

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 or Task<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 call ConfigureAwait(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();

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions