Wenfengcheng / xamarin-notes

xamarin journal
MIT License
3 stars 0 forks source link

Use ConfigureAwait to improve your application #49

Open Wenfengcheng opened 5 years ago

Wenfengcheng commented 5 years ago

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/#