Freigeben über


Unit testing multi-threaded WPF applications

While working to make a WPF application more responsive by offloading time consuming operations to .net 4.5 tasks (one of my favorite things!), I ran into a problem.  Some of the unit tests just hung.  This was because code running on the UI thread was modified to run a task, which eventually invoked a method on using WPF's Dispatcher.CurrentDispatcher to get the final piece done back on the UI thread.  All well and good when the app is running.  But our unit tests do not create an application, so there is no message pump running.  Fortunately there is an excellent blog post which provides some code to run your own message pump in your unit tests: https://blog.rees.biz/2011/01/unit-testing-worker-threads-and-wpf.html.  In particular the DispatcherHelper class towards the end of the post is very, very useful.  Just keep running the DoEvents method until either the change you are expecting (on the UI thread) occurs, or you timeout and consider the unit test failed.