异步一路下来? [英] Async all the way down?
问题描述
试图了解新的异步/待机模式,我有一个问题,我无法找到答案,即我是否应该装饰我的方法与异步的,如果我打算打电话给其他异步功能的方法,或只是返回工作
s其中合适呢?
Trying to understand the new async/await pattern, I have one question which I can't find an answer to, namely if I should decorate my methods with async, if I intend to call those methods from other async functions, or just return Task
s where appropriate?
换句话说,这些类A,B或C的这是最好的,
In other words, which of these classes A, B or C is best, and why?
class A<T>
{
public async Task<T> foo1() //Should be consumed
{
return await foo2();
}
public async Task<T> foo2() //Could be consumed
{
return await foo3();
}
private async Task<T> foo3() //Private
{
return await Task.Run(...);
}
}
class B<T>
{
public async Task<T> foo1() //Should be consumed
{
return await foo2();
}
public async Task<T> foo2() //Could be consumed
{
return await foo3();
}
private Task<T> foo3() //Private
{
return Task.Run(...);
}
}
class C<T>
{
public async Task<T> foo1() //Should be consumed
{
return await foo2();
}
public Task<T> foo2() //Could be consumed
{
return foo3();
}
private Task<T> foo3() //Private
{
return Task.Run(...);
}
}
这似乎是多余的overdecorate方法,所以我很自然地倚向 C
,但在同一时间,感觉有点尴尬与任务&LT工作; T&GT ;
,除非您使用等待
关键字
It seems redundant to overdecorate methods so I naturally lean toward C
, but at the same time it feels somewhat awkward to work with Task<T>
unless you use the await
keyword.
推荐答案
这两个版本有效的工作是相同的,唯一不同的是,当你使用等待
在这里,你会得到的性能损失(因为国家机器必须建立和延续将最有可能被使用)。
Both versions work effectively the same, the only difference is that when you use await
here, you get some performance penalty (because the state machine must be set up and a continuation will most likely be used).
因此,可以归结为一个权衡:你想对你的方法,由于它是略少可读性的成本在某种程度上更有效率?或者,你愿意牺牲性能可读性?
So, it comes down to a tradeoff: Do you want your methods to be somewhat more efficient at the cost of being slightly less readable? Or are you willing to sacrifice performance for readability?
通常情况下,我会建议你先去为了提高可读性,如果分析告诉你,这是值得的只注重性能。但是,在这种情况下,我觉得在可读性的增加是很小的,所以我可能不会使用等待
。
Usually, I would advise you to go for readability first and only focus on performance if profiling tells you it's worth it. But in this case, I think the increase in readability is small, so I would probably not use await
.
另外请注意,您的类 C
仍然没有走得足够远: foo1()
也没有需要等待
。
Also note that your class C
still doesn't go far enough: foo1()
also doesn't need await
.
这篇关于异步一路下来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!