nullPainter
nullPainter

Reputation: 3056

Are asynchronous callbacks required?

If one has the following method with a callback:

public async Task MethodWithCallback(Action callback)
{
  await _myService.SomeExcitingAsync(); 
  callback();
}

Is it safe/recommended to pass in an asynchronous callback, as in:

await MethodWithCallback(async () =>
  {
    await _myOtherService.AnotherExcitingAsync();
  });

Or is it advised that I provide an async version of my method as below? Does it make any difference?

public async Task MethodWithCallback(Func<Task> callback) {
  await _myService.SomeExcitingAsync(); 
  await callback();
}

Upvotes: 2

Views: 78

Answers (1)

Cory Nelson
Cory Nelson

Reputation: 30011

tl;dr

If the callback code is asynchronous, have the delegate return a Task.

the long

While you can assign an async lambda to an Action, it probably doesn't have the behavior you're expecting. It creates what is equivalent to an async void method.

The result is that while the lambda is async, the caller of the delegate would not be able to wait for it to finish and would not be able to see its result. Any uncaught exceptions would be lost.

While this is allowed by C# and there are extremely rare circumstances where code might be very carefully made with these caveats in mind, the general rule of thumb is to never do this.

Upvotes: 2

Related Questions