async/await with ConfigureAwait's continueOnCapturedContext parameter and SynchronizationContext for asynchronous continuations

后端 未结 1 821
谎友^
谎友^ 2021-01-02 04:18

I would like put the code first and then explain the situation and ask my question based on that:

public partial class MainWindow : Window {

    public Main         


        
相关标签:
1条回答
  • 2021-01-02 04:43

    When you call ConfigureAwait(false), the rest of the method will be executed on a thread pool thread unless the Task you're awaiting is already complete.

    Since GetAsync will almost definitely run asynchronously, I would expect GetStringAsync to run on a thread pool thread.

    public async Task<string> GetValuesAsync() {           
    
        using (var httpClient = new HttpClient()) {
    
            var response = await httpClient
                .GetAsync("http://www.google.com")
                .ConfigureAwait(continueOnCapturedContext: false);
    
            // And now we're on the thread pool thread.
    
            // This "await" will capture the current SynchronizationContext...
            var html = await GetStringAsync();
            // ... and resume it here.
    
            // But it's not the UI SynchronizationContext.
            // It's the ThreadPool SynchronizationContext.
            // So we're back on a thread pool thread here.
    
            // So this will raise an exception.
            html += "Hey...";
            Foo.Text = html;
    
            return html;
        }
    }
    

    Also, in this case, is there a chance for GetStringAsync method to be posted back to UI thread bacuse the httpClient.GetAsync method continuation may be executed inside the UI thread?

    The only way GetStringAsync will run on the UI thread is if GetAsync completes before it's actually awaited. Highly unlikely.

    For this reason, I prefer to use ConfigureAwait(false) for every await once the context is no longer needed.

    0 讨论(0)
提交回复
热议问题