Chris Shepherd Chris Shepherd - 2 months ago 27x
C# Question

Using the WPF Dispatcher in unit tests

I'm having trouble getting the Dispatcher to run a delegate I'm passing to it when unit testing. Everything works fine when I'm running the program, but, during a unit test the following code will not run:

this.Dispatcher.BeginInvoke(new ThreadStart(delegate

foreach (User user in e.Results)
}), DispatcherPriority.Normal, null);

I have this code in my viewmodel base class to get a Dispatcher:

if (Application.Current != null)
this.Dispatcher = Application.Current.Dispatcher;
this.Dispatcher = Dispatcher.CurrentDispatcher;

Is there something I need to do to initialise the Dispatcher for unit tests? The Dispatcher never runs the code in the delegate.

jbe jbe

By using the Visual Studio Unit Test Framework you don’t need to initialize the Dispatcher yourself. You are absolutely right, that the Dispatcher doesn’t automatically process its queue.

You can write a simple helper method “DispatcherUtil.DoEvents()” which tells the Dispatcher to process its queue.

C# Code:

public static class DispatcherUtil
    [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    public static void DoEvents()
        DispatcherFrame frame = new DispatcherFrame();
            new DispatcherOperationCallback(ExitFrame), frame);

    private static object ExitFrame(object frame)
        ((DispatcherFrame)frame).Continue = false;
        return null;

You find this class too in the WPF Application Framework (WAF).