Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use ConfigureAwait to improve your application #49

Open
Wenfengcheng opened this issue Jul 5, 2019 · 0 comments
Open

Use ConfigureAwait to improve your application #49

Wenfengcheng opened this issue Jul 5, 2019 · 0 comments
Labels

Comments

@Wenfengcheng
Copy link
Owner

Though pretty convenient, the previous code in somewhat inefficient in our scenario. We do not actually care whether we are on the main thread or not. So why not stay in the background to free the UI thread ?
This is what the ConfigureAwait method enables to do.

/// <summary>
/// Run a long running task composed of small awaited and configured tasks
/// </summary>
private async Task<int> ProcessConfiguredAsync(int loop)
{
    int result = 0;
    for (int i = 0; i < loop; i++)
    {
        Debug.WriteLine(SynchronizationContext.Current == null);
        await Task.Delay(10).ConfigureAwait(false);
        Debug.WriteLine(SynchronizationContext.Current == null);

        result += i;
    }

    return result;
}

Calling ConfigureAwait(false) after the task means that we do not care if the code after the await, runs on the captured context or not.

https://johnthiriet.com/configure-await/#

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant