Jakie są różnice między używaniem ConfigureAwait (false) a Task.Run?
Rozumiem, że zaleca się używanieConfigureAwait(false)
dlaawait
s w kodzie biblioteki, aby kolejny kod nie działał w kontekście wykonania wywołującego, który mógłby być wątkiem interfejsu użytkownika. Ja też to rozumiemawait Task.Run(CpuBoundWork)
powinien być używany zamiastCpuBoundWork()
z tego samego powodu.
ConfigureAwait
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); //CPU-bound
}
Przykład zTask.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); //CPU-bound
});
}
Jakie są różnice między tymi dwoma podejściami?