I understand that he recommended using ConfigureAwait(false) for await in the library code so that subsequent code does not execute in the context of the caller's execution, which may be a user interface thread. I also understand that await Task.Run(CpuBoundWork) should be used instead of CpuBoundWork() for the same reason.
ConfigureAwait example
public async Task<HtmlDocument> LoadPage(Uri address) { using (var client = new HttpClient()) using (var httpResponse = await client.GetAsync(address).ConfigureAwait(false)) using (var responseContent = httpResponse.Content) using (var contentStream = await responseContent.ReadAsStreamAsync().ConfigureAwait(false)) return LoadHtmlDocument(contentStream);
Example with Task.Run
public async Task<HtmlDocument> LoadPage(Uri address) { using (var client = new HttpClient()) using (var httpResponse = await client.GetAsync(address)) return await Task.Run(async () => { using (var responseContent = httpResponse.Content) using (var contentStream = await responseContent.ReadAsStreamAsync()) return LoadHtmlDocument(contentStream);
What are the differences between the two approaches?
Sam Feb 16 2018-12-13T00: 00Z
source share