异步一路下来?

编程入门 行业动态 更新时间:2024-10-06 23:18:55
本文介绍了异步一路下来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

试图了解新的异步/待机模式,我有一个问题,我无法找到答案,即我是否应该装饰我的方法与异步的,如果我打算打电话给其他异步功能的方法,或只是返回工作 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 Tasks 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.

更多推荐

异步一路下来?

本文发布于:2023-11-30 18:33:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651079.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!