I read this article about Task.ConfigureAwait , which can help prevent deadlocks in asynchronous code.
Looking at this code: ( I know I should not do .Result , but this is part of the question )
private void Button_Click(object sender, RoutedEventArgs e) { string result = GetPageStatus().Result; Textbox.Text = result; } public async Task<string> GetPageStatus() { using (var httpClient = new HttpClient()) { var response = await httpClient.GetAsync("http://www.google.com"); return response.StatusCode.ToString(); } }
This will lead to a deadlock because:
Operation .Result - will block the current thread (i.e. the user interface thread) while it waits for the async operation to complete.
Once the network call is completed, it will try to continue execution of the response.StatusCode.ToString() method in the captured context. (which is blocked, therefore, a dead end).
One solution was to use:
var response = await httpClient.GetAsync("http://www.google.com").ConfigureAwait(false);
But another solution was completely asynchronous (without blocking):
private async void Button_Click(object sender, RoutedEventArgs e) { string result = await GetPageStatus(); Textbox.Text = result; } public async Task<string> GetPageStatus() { using (var httpClient = new HttpClient()) { var response = await httpClient.GetAsync("http://www.google.com"); return response.StatusCode.ToString(); } }
Question:
(I'm trying to understand how this code helps solve the problem - through contextual POV).
Was I right?
- Visualization: (is this the correct thread?)

source share