.NET Create New Dispatcher

I'm actually creating a lot of these dispatchers, I guess the proper way is something along the following lines:

object theLock = new object();
Dispatcher dispatcher = null;

lock (theLock)
{
    new Thread(new ThreadStart(() =>
    {
        lock (theLock)
        {
            dispatcher = Dispatcher.CurrentDispatcher;
            Monitor.Pulse(theLock);
        }
        Dispatcher.Run();
    })).Start();

    Monitor.Wait(theLock);
}

dispatcher.Invoke(...);

It seems complicated with all the locking, but theoretically the Start() method can return before dispatcher is actually set, so a call to to it might result in a NullReferenceException without the locks.


Dispatcher.FromThread(...) will not create a Dispatcher and will return null if a Dispatcher has not already been created for the thread. To create a Dispatcher for a thread, you will have to access Dispatcher.CurrentDispatcher at least once on your CheckLoopThread. As it says on MSDN for Dispatcher.CurrentDispatcher:

If a Dispatcher is not associated with the current thread, a new Dispatcher will be created. This is not the case with the FromThread method. FromThread will return null if there is not a dispatcher associated with the specified thread


Why locking?

I prefer:

Dispatcher myDispatcher = null;

ManualResetEvent dispatcherReadyEvent = new ManualResetEvent(false);

new Thread(new ThreadStart(() =>
{
    myDispatcher = Dispatcher.CurrentDispatcher;
    dispatcherReadyEvent.Set();
    Dispatcher.Run();
})).Start();

dispatcherReadyEvent.WaitOne();

myDispatcher.Invoke(...);