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

不打扰是莪最后的温柔 提交于 2019-11-30 12:23:38

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!