.net Dispatcher.Invoke()在NUnit测试中抛出TaskCanceledException
我试图通过使用一个接口从我们的视图模型中抽象出.net Dispatcher.Invoke()在NUnit测试中抛出TaskCanceledException,.net,nunit,dispatcher,.net,Nunit,Dispatcher,我试图通过使用一个接口从我们的视图模型中抽象出调度程序。我已经创建了此接口的模拟实现,如下所示: public class MockIDispatcher : IDispatcher, IDisposable { public MockIDispatcher() { var dispatcherThread = new Thread(Dispatcher.Run) { IsBackground = true }; dispatcherThread.
调度程序。我已经创建了此接口的模拟实现,如下所示:
public class MockIDispatcher : IDispatcher, IDisposable
{
public MockIDispatcher()
{
var dispatcherThread = new Thread(Dispatcher.Run) { IsBackground = true };
dispatcherThread.SetApartmentState(ApartmentState.STA);
dispatcherThread.Start();
while ((Dispatcher = Dispatcher.FromThread(dispatcherThread)) == null) Thread.Yield(); // need to wait until the thread we created has started its dispatcher
}
internal Dispatcher Dispatcher { get; }
/* ... more implementation here */
}
我创建了一个虚拟NUnit测试,如下所示,但是对Dispatcher.Invoke()
的调用抛出了一个TaskCanceledException
[Test]
public void TestPoc()
{
var foo = new MockIDispatcher();
foo.Dispatcher.Invoke(() =>
{
Debug.WriteLine("Hey there!");
});
}
关于如何让这段代码工作有什么建议吗?我想在幕后使用调度器,以便更轻松地处理SynchronizationContext
s之类的事情。问题似乎在于如何在构造函数中获得Dispatcher
。我更改了如下所示的构造函数,这就解决了问题。看起来您可能需要首先在线程上实际调用Dispatcher.CurrentDispatcher
。调用Dispatcher.Run()
是不够的
public MockIDispatcher()
{
using (var mre = new ManualResetEvent(false))
{
Dispatcher dispatcher = null;
var dispatcherThread = new Thread(() =>
{
dispatcher = Dispatcher.CurrentDispatcher;
// ReSharper disable once AccessToDisposedClosure Not Possible because we are waiting inside the using loop
mre.Set();
try { Dispatcher.Run(); } catch { /* swallow exceptions */ }
}) { IsBackground = true };
dispatcherThread.SetApartmentState(ApartmentState.STA);
dispatcherThread.Start();
mre.WaitOne();
Dispatcher = dispatcher;
}
}