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

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.

Answers


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

Fluent NHibernate: How to create one-to-many bidirectional mapping?

nhibernate fluent-nhibernate nhibernate-mapping

Basic question: How to I create a bidirectional one-to-many map in Fluent NHibernate?

multicast windows 2008 r2 multicast

windows windows-server-2008-r2 multicast

Has anyone seem a problem with reading multicast on a Windows server 2008 R2 machine?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.