[Test]
public void A()
{
var d = Dispatcher.CurrentDispatcher;
Action action = () => Console.WriteLine("Dispatcher invoked me!");
var worker = new BackgroundWorker();
worker.DoWork += SomeWork;
//worker.RunWorkerAsync( (Action) delegate { Console.WriteLine("This works!"); } );
worker.RunWorkerAsync((Action) delegate { d.Invoke(action); } );
System.Threading.Thread.Sleep(2500);
}
private void SomeWork(object sender, DoWorkEventArgs e)
{
(e.Argument as Action)();
}
This block of code doesn't throw an exception. At the same time, Dispatcher.Invoke does nothing. I found that odd.
I extracted a helper method into a base ViewModel. Worker threads used this method DoOnUIThread() to avoid the thread affinity issue. However in my unit-tests, I find that attempting to test the view model objects results in failures due to the above issue.
I could move this whole behavior out into a pluggable dependency that I could substitute in my tests. e.g. ViewModelBase depends on UIThreadExecutor.Execute(Action) and I use a fake that just calls the action in my tests. However I'm curious as to why Dispatcher behaves the way it does..