Multi-thread UI in WPF

  1. 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.

  2. 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.

  3. Below is the pseudo-code in main thread:

    for(...) {

      //Option A: Application.DoEvents(); 
      //Option B: Dispatcher.Invoke to update UI in background thread
        return;  //Stop the time-consuming function


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...

Any thoughts?

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.

Need Your Help

Download a file with Adobe AIR

flex actionscript air

How do I download a file from the internet in a Flex based AIR application.

Get a URL in a JSP file to run through the controller servlet

jsp url servlets controller

So I have a list of events (objects). I want to make it so that when you click an event title, additional information will enfold for that event. But if I write it like this, it won't interact with...