3

I have read many post about Application.Current.Dispacherbeing null when unit testing. which is the exact problem that i am having. I have found This which is exactly what I am looking for. However, it seems that when I go to implement this I cannot compile. With the error of:

Cannot access private constructor 'Dispatcher' here.

In the above post they state that there are many ways to implement the code that I have below. As he hasn't checked for multi-threading safety checks. How can i do these checks and get this to compile?

    public static Dispatcher RootDispatcher
    {
        get
        {
            if (_rootDispatcher == null)
            {

                if (Application.Current != null)
                {
                    _rootDispatcher = Application.Current.Dispatcher;
                }
                else
                {
                    var thread = Thread.CurrentThread;
                    _rootDispatcher = new Dispatcher(thread);
                }
            }
            return _rootDispatcher;
        }
        internal set { _rootDispatcher = value; }
    }
Community
  • 1
  • 1
JamTay317
  • 1,017
  • 3
  • 18
  • 37

1 Answers1

4

The compile error is due to the fact that the constructor you're trying to use is in fact private (and you're calling it with a an argument that it doesn't take)

Looking at the documentation of Dispatcher.Current, it says:

Gets the for the thread currently executing and creates a new if one is not already associated with the thread.

So, you can use:

  • _rootDispatcher = Dispatcher.CurrentDispatcher;

resulting in a Dispatcher instance.

As an optimization you can just use Dispatcher.CurrentDispatcher as 'RootDispatcher' all the time. No matter if Application.Current exists.

If you hit this code in both production and test, you'll need to make a distinction between these scenarios. Use the Application's Dispatcher in production, and use 'any' Dispatcher (Dispatcher.Current) in unit tests, because the Application is not there.

LoekD
  • 11,402
  • 17
  • 27
  • thank you, so should i not create the rootdispacher class? – JamTay317 Jul 22 '16 at 12:22
  • Dispatcher.CurrentDispatcher will return a new Dispatcher instance, if the current thread doesn't have one attached to it already. So it should be safe for unit testing scenarios. If you have this code in both production and test, you'll need to make a distinction. – LoekD Jul 22 '16 at 13:31