.NET Create New Dispatcher

René Sackers picture René Sackers · Jul 15, 2011 · Viewed 8k times · Source

I am trying to create a second thread with dispatcher so that I can have the primary dispatcher (for the UI) completely stress-free, and have the UI constantly respondant.

Now, I could create multiple threads for each sub (or void in C#), but isn't it possible for me to create one new thread and grab it's dispatcher, and invoke to that? This is what I've done:

Private CheckLoopThread As New System.Threading.Thread(New System.Threading.ThreadStart(AddressOf CheckLoop))

CheckLoopThread.Priority = System.Threading.ThreadPriority.Lowest
CheckLoopThread.Start()
Dim Test As Windows.Threading.Dispatcher = Windows.Threading.Dispatcher.FromThread(CheckLoopThread)

However, the variable "Test" is after execution "Nothing". How is this possible? Is the another way to create a second dispatcher?

Answers are appreciated in any .NET form. Visual Basic or C#. I am working in VB.NET WPF on the .NET 4.0 framework.

Thanks in advance.

Answer

Jeroen van Langen picture Jeroen van Langen · Jul 30, 2013

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(...);