简体   繁体   English

是否需要异步回调?

[英]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();
}

tl;dr tl;博士

If the callback code is asynchronous, have the delegate return a Task .如果回调代码是异步的,则让委托返回一个Task

the long长的

While you can assign an async lambda to an Action , it probably doesn't have the behavior you're expecting.虽然您可以将异步 lambda 分配给Action ,但它可能没有您期望的行为。 It creates what is equivalent to an async void method.它创建了等效于async void方法的内容。

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.结果是,虽然 lambda 是异步的,但委托的调用者将无法等待它完成,也无法看到它的结果。 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.尽管 C# 允许这样做,并且在极少数情况下可能会非常小心地编写代码并考虑到这些警告,但一般的经验法则是永远不要这样做。

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

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