-2

There is a function

async Task MyFuncation(Func<Task> f)
{
    // do something
    //
    await f();
}

Sometimes I need to call the function but don't have anything for parameter f so I pass it async () => { }. Is there a noop function for it?

await RunMyFuncation(async () => { }); // I still need to call Run
ca9163d9
  • 27,283
  • 64
  • 210
  • 413

1 Answers1

2

The noop that you are looking for is Task.CompletedTask.

Gets a task that has already completed successfully.

However, you still need to pass a lambda since the method requires a Func<T> not a Task as an argument.

await Run(() => Task.CompletedTask);

This might not be that different from using a empty block as you suggested.

Mehrzad Chehraz
  • 5,092
  • 2
  • 17
  • 28
  • Interesting, my Visual Studio cannot prompt up `CompletedTask` after typing `Task.`. – ca9163d9 Mar 20 '19 at 22:38
  • @Dai, I still need to call `Run()`. I just don't have anything for the paramter of `f` of `Run()`. – ca9163d9 Mar 20 '19 at 22:45
  • @Dai `Run` in a user defined method with contains code. Maybe you confused it with `Task.Run`. – Mehrzad Chehraz Mar 20 '19 at 22:47
  • @RufusL `Run` is a user defined method returning a Task. You can definitely use `await` to wait for the method to complete. – Mehrzad Chehraz Mar 20 '19 at 22:48
  • 1
    @RufusL We don't know if the method is being called inside a async method or not, I assumed it is, so I added await before it. Fixed the error as well. – Mehrzad Chehraz Mar 20 '19 at 22:57
  • Ah, my bad. I see even in the OP's original post he's calling it with `await`. I'll delete that comment! I like this answer, since it seems more "intentional" than what the OP was originally doing. – Rufus L Mar 20 '19 at 23:12