I have this simple code in a WPF application:
ThreadStart start = delegate()
{
Thread.Sleep(5000);
Console.WriteLine("HEY!");
Dispatcher.CurrentDispatcher.BeginInvoke(
DispatcherPriority.Normal,
new Action(
delegate()
{
Console.WriteLine("Inside invoke?!");
}
)
);
};
new Thread(start).Start();
HEY! gets printed after a moment as it should and the application is not blocked as one would expect from the use of threads, however, why do I never see Inside invoke?!? I also tried different priorities like Send, which I believe is the highest priority.
I’ve also tried putting breakpoints inside, and it never stopped there.
Few basics first –
Issue with the code –
You are placing the delegate on Dispatcher queue for the secondary thread you have created. But before the secondary thread gets the time to execute it, your secondary thread exited and hence its dispatcher. That’s why the delegate never get executed.
There are two ways you can achieve this –
Either queue the delegate on the dispatcher synchronously like this –
Or you can queue it on the dispatcher of your main thread (often called UI thread) like this –