简体   繁体   English

在`Task.Run`中使用`Result`有多有效?

[英]How valid is it to use `Result` inside `Task.Run`

In Akka.Net there is the nice design inside an actor, to start a task with Task.Run and pipe the result back to the actor: 在Akka.Net中,actor内有一个不错的设计,可以使用Task.Run启动任务, Task.Run结果通过管道Task.Run回actor:

Task.Run(() => Method(...)).PipeTo(self);

Note, there is no IO involved. 注意,不涉及IO。
Inside
Model Method(...)
there is a little bit of pre-processing, then I have to wait on a call to a Task<Model> and a little bit of post-processing. 有一些预处理,然后我必须等待对Task<Model>的调用和一些后处理。
Task<Model> is in a third-party library, I cannot change it. Task<Model>在第三方库中,我无法更改。
Currently I do var model = proxy.GetModel(..).Result inside a try catch . 目前我在try catch执行var model = proxy.GetModel(..).Result
A possible AggregateException is taken into account. 考虑到可能的AggregateException

Another idea is to use this with await . 另一个想法是将其与await一起使用。
var model = await proxy.GetModel(..) inside a try catch and changing the signature to try catch var model = await proxy.GetModel(..)更改为
async Task<Model> Method(...)

How should I change the call to Method in the actor? 我应该如何在actor中更改对Method的调用?

Task.Run(() => Method(...).Result).PipeTo(self);
Task.Run(async () => await Method(...)).PipeTo(self);

Which approach is better, what is the difference? 哪种方法更好,有什么区别?

Result blocks a thread and wraps any exceptions in AggregateException . Result阻塞线程,并将所有异常包装在AggregateException For these reasons, I generally prefer await . 由于这些原因,我通常更喜欢await

In this case, you can elide the async / await : 在这种情况下,您可以忽略async / await

// Same as:
// Task.Run(async () => await Method(...)).PipeTo(self);
Task.Run(() => Method(...)).PipeTo(self);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM