4

I need to pass an argument of type Task to some function that is not presented here. Inside the function this task will be executed in async way. If there a difference between these three ways to pass it:

1.

Task.Run((Func<Task>)(async () => Foo = await OperateAsync(id)))

2.

Task.Run(async () => Foo = await OperateAsync(id))

3.

((Func<Task>)(async () => Foo = await OperateAsync(id))).Invoke()
AsValeO
  • 2,859
  • 3
  • 27
  • 64

1 Answers1

4

Yes.

1 and 2 differ in which overload of Task.Run gets called. The latter passes through the result.

1 and 2 force OperateAsync to the thread pool, 3 doesn't, which can be very visible depending on other details. For example, in desktop applications, if OperateAsync ends up accessing UI elements, it must not be called using Task.Run.

  • Is second approach is better than first in terms of performance? – AsValeO May 13 '17 at 17:04
  • 1
    @AsValeO It should be the same. If either is measurably faster, I think that's a missed opportunity for the other. If you were asking because of the delegate construction, keep in mind that that happens implicitly in the second one as well. –  May 13 '17 at 17:18