Multi-thread UI in WPF
I have two UI threads, one is the main thread and the other is a background thread whose ApartmentState is STA. Each thread creates its own window and the background window has a "Cancel" button on it.
The main thread has a function which is busy and needs quite a long time to finish. I hope once the "Cancel" button is clicked, the main thread should stop the time-consuming function.
Below is the pseudo-code in main thread:
//Option A: Application.DoEvents(); //Option B: Dispatcher.Invoke to update UI in background thread if(cancel) return; //Stop the time-consuming function else DoSomething;
The strange thing is that the click event on "Cancel" button is NOT captured or handled by the background thread. IMO, each thread has its own message queue, and when I click the "Cancel" button, this message should be queued and processed by the background thread immediately, but according to my test locally, this is not true, the background thread never handles the button click event...
BTW, I think there are two ways to overcome the above issue, one is to use Application.DoEvents, and the other is to leverage Dispatcher.Invoke. But I'm still curious why the background thread can NOT handle the message immediately. Thanks in advance.
In general, having two user interface threads is often a bad idea, and completely unnecessary.
You'd typically have a single user interface thread, and just move the actual computational work into a background thread. User interface updates would be marshaled back to the main thread as needed. BackgroundWorker is great for this in many cases.
As for cancellation, this is typically best handled using the frameworks cooperative cancelation model which is built around CancellationTokenSource and CancellationToken. These were designed with use across multiple threads in mind, and automatically handle the proper memory barriers required.