這並不容易,但也不是那麼難。你需要做的是啓動一個作爲STA設置的工作線程,並啓動它的Dispatcher運行時。一旦你有了那個工作人員,你可以從單元測試線程派遣工作,顯然,這些工作並未初始化。因此,首先,這裏是你如何啓動調度線程測試設置:
this.dispatcherThread = new Thread(() =>
{
// This is here just to force the dispatcher infrastructure to be setup on this thread
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
Trace.WriteLine("Dispatcher worker thread started.");
}));
// Run the dispatcher so it starts processing the message loop
Dispatcher.Run();
});
this.dispatcherThread.SetApartmentState(ApartmentState.STA);
this.dispatcherThread.IsBackground = true;
this.dispatcherThread.Start();
現在,如果你想徹底關閉該線程記在你的測試清理,我建議你做什麼,你只需做以下:
Dispatcher.FromThread(this.dispatcherThread).InvokeShutdown();
所以,所有的基礎設施的東西的方式進行,這裏就是你需要在你的測試,該線程執行的事情。
public void MyTestMethod
{
// Kick the test off on the dispatcher worker thread synchronously which will block until the work is competed
Dispatcher.FromThread(this.dispatcherThread).Invoke(new Action(() =>
{
// FromCurrentSynchronizationContext will now resolve to the dispatcher thread here
}));
}
它的工作,非常感謝你! – Alberto