nunit如何成功等待async void方法完成?

在C#中使用async/await时,一般规则是避免async void因为它几乎是火,忘了,如果没有从方法发送返回值,则应该使用Task 。 说得通。 但奇怪的是,在本周早些时候,我正在为我编写的一些async方法编写一些unit testing,并注意到NUnit建议将async测试标记为void或返回Task 。 然后我试了一下,果然,它奏效了。 这看起来很奇怪,因为nunit框架如何能够运行该方法并等待所有异步操作完成? 如果它返回Task,它可以等待任务,然后做它需要做的事情,但是如果它返回void它怎么能把它拉下来呢?

所以我破解了源代码并找到了它。 我可以在一个小样本中重现它,但我根本无法理解它们正在做什么。 我想我对SynchronizationContext以及它是如何工作的了解不够。 这是代码:

 class Program { static void Main(string[] args) { RunVoidAsyncAndWait(); Console.WriteLine("Press any key to continue. . ."); Console.ReadKey(true); } private static void RunVoidAsyncAndWait() { var previousContext = SynchronizationContext.Current; var currentContext = new AsyncSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(currentContext); try { var myClass = new MyClass(); var method = myClass.GetType().GetMethod("AsyncMethod"); var result = method.Invoke(myClass, null); currentContext.WaitForPendingOperationsToComplete(); } finally { SynchronizationContext.SetSynchronizationContext(previousContext); } } } public class MyClass { public async void AsyncMethod() { var t = Task.Factory.StartNew(() => { Thread.Sleep(1000); Console.WriteLine("Done sleeping!"); }); await t; Console.WriteLine("Done awaiting"); } } public class AsyncSynchronizationContext : SynchronizationContext { private int _operationCount; private readonly AsyncOperationQueue _operations = new AsyncOperationQueue(); public override void Post(SendOrPostCallback d, object state) { _operations.Enqueue(new AsyncOperation(d, state)); } public override void OperationStarted() { Interlocked.Increment(ref _operationCount); base.OperationStarted(); } public override void OperationCompleted() { if (Interlocked.Decrement(ref _operationCount) == 0) _operations.MarkAsComplete(); base.OperationCompleted(); } public void WaitForPendingOperationsToComplete() { _operations.InvokeAll(); } private class AsyncOperationQueue { private bool _run = true; private readonly Queue _operations = Queue.Synchronized(new Queue()); private readonly AutoResetEvent _operationsAvailable = new AutoResetEvent(false); public void Enqueue(AsyncOperation asyncOperation) { _operations.Enqueue(asyncOperation); _operationsAvailable.Set(); } public void MarkAsComplete() { _run = false; _operationsAvailable.Set(); } public void InvokeAll() { while (_run) { InvokePendingOperations(); _operationsAvailable.WaitOne(); } InvokePendingOperations(); } private void InvokePendingOperations() { while (_operations.Count > 0) { AsyncOperation operation = (AsyncOperation)_operations.Dequeue(); operation.Invoke(); } } } private class AsyncOperation { private readonly SendOrPostCallback _action; private readonly object _state; public AsyncOperation(SendOrPostCallback action, object state) { _action = action; _state = state; } public void Invoke() { _action(_state); } } } 

运行上面的代码时,您会注意到在按任意键继续消息之前显示完成hibernate和完成等待消息,这意味着异步方法以某种方式等待。

我的问题是,有人可以解释这里发生了什么吗? 什么是SynchronizationContext (我知道它用于将工作从一个线程发布到另一个线程)但我仍然对如何等待所有工作完成感到困惑。 提前致谢!!

SynchronizationContext允许将工作发布到由另一个线程(或线程池)处理的队列 – 通常UI框架的消息循环用于此。 async / awaitfunction在内部使用当前同步上下文在您等待的任务完成后返回到正确的线程。

AsyncSynchronizationContext类实现自己的消息循环。 发布到此上下文的工作将添加到队列中。 当你的程序调用WaitForPendingOperationsToComplete(); ,该方法通过从队列中抓取工作并执行它来运行消息循环。 如果在Console.WriteLine("Done awaiting");上设置断点Console.WriteLine("Done awaiting"); ,您将看到它在WaitForPendingOperationsToComplete()方法中的主线程上运行。

此外, async / awaitfunction调用OperationStarted() / OperationCompleted()方法,以便在async void方法启动或完成执行时通知SynchronizationContext

AsyncSynchronizationContext使用这些通知来计算正在运行但尚未完成的async方法的数量。 当此计数达到零时, WaitForPendingOperationsToComplete()方法停止运行消息循环,控制流返回给调用者。

要在调试器中查看此过程,请在同步上下文的PostOperationStartedOperationCompleted方法中设置断点。 然后逐步执行AsyncMethod调用:

  • 调用AsyncMethod ,.NET首先调用OperationStarted()
    • _operationCount设置为1。
  • 然后AsyncMethod的主体开始运行(并启动后台任务)
  • await语句中, AsyncMethod在任务尚未完成时产生控制权
  • currentContext.WaitForPendingOperationsToComplete(); 被叫
  • 队列中还没有可用的操作,因此主线程在_operationsAvailable.WaitOne();
  • 在后台线程:
    • 在某些时候任务完成睡眠
    • 输出: Done sleeping!
    • 委托完成执行,任务标记为完成
    • 调用Post()方法,将一个表示AsyncMethod剩余部分的AsyncMethod
  • 主线程被唤醒,因为队列不再是空的
  • 消息循环运行continuation,从而恢复执行AsyncMethod
  • 输出: Done awaiting
  • AsyncMethod完成执行,导致.NET调用OperationComplete()
    • _operationCount递减为0,这将消息循环标记为完成
  • 控制返回消息循环
  • 消息循环结束,因为它被标记为完成, WaitForPendingOperationsToComplete返回给调用者
  • 输出: Press any key to continue. . . Press any key to continue. . .