Reputation: 1017
I have read many post about Application.Current.Dispacher
being 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; }
}
Upvotes: 3
Views: 2620
Reputation: 11470
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.
Upvotes: 4