如何等待异步委托
在其中一个MVAvideo中,我看到了下一个结构:
static void Main(string[] args) { Action testAction = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("After first delay"); await Task.Delay(100); Console.WriteLine("After second delay"); }; testAction.Invoke(); }
执行结果将是:
In Press any key to continue . . .
它是完美的编译,但现在我没有看到任何方式等待它。 我可能会在调用后放置Thread.Sleep
或Console.ReadKey
,但这不是我想要的。
那么应该如何修改这个代表以使其变得等待?(或者至少我如何跟踪执行完成?)
这些代表有实际用途吗?
为了等待某事,它必须是等待的 。 由于void
不是这样,您无法等待任何Action
委托。
等待是实现GetAwaiter
方法的任何类型,它返回一个实现INotifyCompletion
或ICriticalNotifyCompletion
的类型,例如Task
和Task
。
如果要等待委托,请使用Func
,它与具有以下签名的命名方法等效:
public Task Func()
因此,为了等待,将您的方法更改为:
static void Main(string[] args) { Func testFunc = async () => { Console.WriteLine("In"); await Task.Delay(100); Console.WriteLine("First delay"); await Task.Delay(100); Console.WriteLine("Second delay"); }; }
现在你可以等待它:
await testFunc();
“Async void仅适用于顶级事件处理程序”,
最近我发现NUnit能够await
async void
测试。 以下是它如何工作的好描述: nunit如何成功等待异步void方法完成?
你不会在常规任务中使用它,但很高兴知道它是可能的