难道是有利的,在一个库,直接返回任务通过调用另一个库使用ConfigureAwait(假的)? [英] Is it advantageous to use ConfigureAwait(false) in a library that directly returns a Task from a call to another library?
问题描述
后续这个问题。我有很多异步方法库,薄包装 的HttpClient
。切实他们只是做一些设置,并直接返回工作
从的HttpClient
调用返回的:
Follow-up to this question. I have a library with many async methods that thinly wrap HttpClient
. Effectively they just do some setup and directly return the Task
returned from the HttpClient
call:
public Task DoThingAsyc() {
// do some setup
return httpClient.DoThingAsync();
}
我在考虑是否 ConfigureAwait(假)
添加到这些电话。在prevailing智慧似乎是是的,总是这样,在图书馆。但在这种情况下,它会介绍一些(也许是可以忽略不计)的开销,因为 ConfigureAwait
返回 ConfiguredTaskAwaitable
这将需要为了不改变方法的签名被包裹恢复成工作
。当然不难code:
I'm pondering whether to add ConfigureAwait(false)
to these calls. The prevailing wisdom seems to be "yes, always do that in libraries." But in this case, it would introduce some (perhaps negligible) overhead, because ConfigureAwait
returns a ConfiguredTaskAwaitable
which would need to be wrapped back into a Task
in order to not change the method signature. Certainly not hard to code:
public async Task DoThingAsyc() {
// do some setup
return await httpClient.DoThingAsync().ConfigureAwait(false);
}
我的问题是,的效率优势ConfigureAwait(假)
可能超过它在这种情况下,引入额外的开销?什么上面的例子将被认为是更好的做法?
My question is, will the efficiency benefits of ConfigureAwait(false)
likely outweigh the extra overhead introduced in this case? What example above would be considered the better practice?
推荐答案
没有,不这样做。
既然你不使用等待
,你不应该提前配置它。这是你的库的调用者做了 ConfigureAwait
通话的责任。而来电者可能想叫 ConfigureAwait(真)
而不是 ConfigureAwait(假)
- 你不知道这一点。
Since you're not using await
, you're not supposed to configure for it in advance. It's the responsibility of the caller of your library to do the ConfigureAwait
call. And the caller may well want to call ConfigureAwait(true)
instead of ConfigureAwait(false)
- you don't know that.
调用 ConfigureAwait(假)
库code是最好的做法,只有当的您的等待着它在库中。
Calling ConfigureAwait(false)
in library code is best practice only when you await on it in the library.
在大多数情况下的,code是这样的:
In most cases, code like this:
Task<Something> DoSomethigAsync()
{
return await DoSomethingElseAsync().ConfigureAwait(false);
}
等同于:
Task<Something> DoSomethigAsync()
{
return DoSomethingElseAsync();
}
如果 DoSomethingElseAsync
尊重工作
的合同(例如,如果它返回一个失败工作
,而不是抛出异常)。
if DoSomethingElseAsync
respects the Task
contract (for instance if it returns a failed Task
instead of throwing exceptions).
创建只是增加一层包裹code,没有附加价值的附加状态机的 - 你最好回报工作
直接
Creating an additional state machine for that is just adding one layer of wrapping code with no added value - you'd better return the Task
directly.
在换句话说:你的无效率的好处任何的从这样做,恰恰相反
In other words: you get no efficiency benefit whatsoever from doing this, quite the contrary.
这篇关于难道是有利的,在一个库,直接返回任务通过调用另一个库使用ConfigureAwait(假的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!