-1

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:

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

Note, there is no IO involved.
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> is in a third-party library, I cannot change it.
Currently I do var model = proxy.GetModel(..).Result inside a try catch.
A possible AggregateException is taken into account.

Another idea is to use this with await.
var model = await proxy.GetModel(..) inside a try catch and changing the signature to
async Task<Model> Method(...)

How should I change the call to Method in the actor?

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

Which approach is better, what is the difference?

Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
Gerard
  • 13,023
  • 14
  • 72
  • 125

1 Answers1

2

Result blocks a thread and wraps any exceptions in AggregateException. For these reasons, I generally prefer await.

In this case, you can elide the async/await:

// Same as:
// Task.Run(async () => await Method(...)).PipeTo(self);
Task.Run(() => Method(...)).PipeTo(self);
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Without async-await keywords, I will have to use the `Result` of the task inside `Method(..)` because my code was somewhat simplified and the post-processing inside `Method(..)` uses the result - allthough I could refactor that. – Gerard May 11 '19 at 13:39
  • @Gerard: No. You can have `Method` use `async`/`await` just fine, with either form of `Task.Run`. – Stephen Cleary May 12 '19 at 00:48