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
When you call ConfigureAwait(false)
, the rest of the method will be executed on a thread pool thread unless the Task
you're await
ing 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 await
ed. Highly unlikely.
For this reason, I prefer to use ConfigureAwait(false)
for every await
once the context is no longer needed.