multithreading - Multi-thread UI in WPF -


  1. i have 2 ui threads, 1 main thread , other background thread apartmentstate sta. each thread creates own window , background window has "cancel" button on it.

  2. the main thread has function busy , needs quite long time finish. hope once "cancel" button clicked, main thread should stop time-consuming function.

  3. below pseudo-code in main thread:

    for(...) {

      //option a: application.doevents();    //option b: dispatcher.invoke update ui in background thread   if(cancel)         return;  //stop time-consuming function   else          dosomething; 

    }

the strange thing click event on "cancel" button not captured or handled background thread. imo, each thread has own message queue, , when click "cancel" button, message should queued , processed background thread immediately, according test locally, not true, background thread never handles button click event...

any thoughts?

btw, think there 2 ways overcome above issue, 1 use application.doevents, , other leverage dispatcher.invoke. i'm still curious why background thread can not handle message immediately. in advance.

in general, having 2 user interface threads bad idea, , unnecessary.

you'd typically have single user interface thread, , move actual computational work background thread. user interface updates marshaled main thread needed. backgroundworker great in many cases.

as cancellation, typically best handled using frameworks cooperative cancelation model built around cancellationtokensource , cancellationtoken. these designed use across multiple threads in mind, , automatically handle proper memory barriers required.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -