What are the differences between using ConfigureAwait(false) and Task.Run?

后端 未结 4 1974
感动是毒
感动是毒 2020-12-22 22:53

I understand that it\'s recommended to use ConfigureAwait(false) for awaits in library code so that subsequent code does not run in the caller\'s e

4条回答
  •  旧巷少年郎
    2020-12-22 23:06

    As a side note, in both cases LoadPage() could still block your UI thread, because await client.GetAsync(address) needs time to create a task to pass to ConfigureAwait(false). And your time consuming operation might have already started before task is returned.

    One possible solution is to use SynchronizationContextRemover from here:

    public async Task LoadPage(Uri address)
    {
        await new SynchronizationContextRemover();
    
        using (var client = new HttpClient())
        using (var httpResponse = await client.GetAsync(address))
        using (var responseContent = httpResponse.Content)
        using (var contentStream = await responseContent.ReadAsStreamAsync())
            return LoadHtmlDocument(contentStream); //CPU-bound
    }
    

提交回复
热议问题