在 C# 中使用async/await
时,一般规则是避免async void
,因为这几乎是一劳永逸,Task
如果没有从方法发送返回值,则应该使用 a。说得通。奇怪的是,本周早些时候我正在为我编写的一些async
方法编写一些单元测试,并注意到 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);
}
}
}
运行上述代码时,您会注意到 Done Sleeping 和 Done awaiting 消息显示在Press any key to continue 消息之前,这意味着异步方法正在等待。
我的问题是,有人可以解释一下这里发生了什么吗?究竟是什么SynchronizationContext
(我知道它用于将工作从一个线程发布到另一个线程)但我仍然对我们如何等待所有工作完成感到困惑。提前致谢!!