Warm tip: This article is reproduced from stackoverflow.com, please click
asynchronous c# task

How to use ConfigureAwait on async methods

发布于 2020-03-27 10:25:51

I am looking into correct uses of ConfigureAwait I have identified a valid use case for ConfigureAwait (i.e. after the await does not require the calling thread synchronisationcontext) and couldn't see any advice on using ConfigureAwait on async methods

My code looks like the following

Public async Task StartMyProgram()
{
     await RunBackgroundTask();
}

Private async Task RunBackgroundTask()
{
     await Task.Delay(5000);
}

To use ConfigureAwait correctly am I assuming that this should be used on both await calls like the below code:

Public async Task StartMyProgram()
{
     await RunBackgroundTask().ConfigureAwait(false);
}

Private async Task RunBackgroundTask()
{
     await Task.Delay(5000).ConfigureAwait(false);
}

or do I just need it on the private RunBackgroundTask method?

Questioner
user1
Viewed
90
Stephen Cleary 2019-07-03 23:29

or do I just need it on the private RunBackgroundTask method?

Each method should make its ConfigureAwait(false) decision on its own. This is because each method captures its own context at await, regardless of what its caller/called methods do. ConfigureAwait configures a single await; it doesn't "flow" at all.

So, RunBackgroundTask needs to determine "do I need to resume on my context?" If no, then it should use ConfigureAwait(false).

And StartMyProgram needs to determine "do I need to resume on my context?" If no, then it should use ConfigureAwait(false).