什么是使用ConfigureAwait(假)和Task.Run之间的区别? [英] What are the differences between using ConfigureAwait(false) and Task.Run?

查看:2946
本文介绍了什么是使用ConfigureAwait(假)和Task.Run之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,它是推荐使用 ConfigureAwait(假)等待 S在库code所以后续code不会在调用者的执行环境中运行,这可能是一个UI线程。我也明白,等待Task.Run(CpuBoundWork)应该用来代替 CpuBoundWork()出于同样的原因。

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 execution context, which could be a UI thread. I also understand that await Task.Run(CpuBoundWork) should be used instead of CpuBoundWork() for the same reason.

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
}

示例与 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); //CPU-bound
        });
}

什么是这两种方法之间的区别是什么?

What are the differences between these two approaches?

推荐答案

当你说 Task.Run ,你是说你有一些CPU的工作要做到这一点可能需要很长的时间,因此应始终在一个线程池中的线程中运行。

When you say Task.Run, you are saying that you have some CPU work to do that may take a long time, so it should always be run on a thread pool thread.

当你说 ConfigureAwait(假),你说的那个异步其余方法不需要原始上下文。 ConfigureAwait 更是一个优化提示的;它没有的总是的意思是继续运行在一个线程池线程。

When you say ConfigureAwait(false), you are saying that the rest of that async method does not need the original context. ConfigureAwait is more of an optimization hint; it does not always mean that the continuation is run on a thread pool thread.

这篇关于什么是使用ConfigureAwait(假)和Task.Run之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆