Making sure OnPropertyChanged() is called on UI thread in MVVM WPF app

前端 未结 5 2084
执念已碎
执念已碎 2020-11-28 07:15

In a WPF app that I\'m writing using the MVVM pattern, I have a background process that doing it\'s thing, but need to get status updates from it out to the UI.

I\'m

5条回答
  •  清歌不尽
    2020-11-28 07:43

    I had a similar scenario just this week (MVVM here too). I had a separate class doing its thing, reporting back status on an event handler. The event handler was being called as expected, and I could see the results coming back right on time with Debug.WriteLine's.

    But with WPF, no matter what I did, the UI would not update until the process was complete. As soon as the process finished, the UI would update as expected. It was as if it was getting PropertyChanged, but waiting for the thread to complete before doing the UI updates all at once.

    (Much to my dismay, the same code in Windows.Forms with a DoEvents and .Refresh() worked like a charm.)

    So far, I've resolved this by starting the process on its own thread:

    //hook up event handler
    myProcess.MyEvent += new EventHandler(MyEventHandler); 
    
    //start it on a thread ...
    ThreadStart threadStart = new ThreadStart(myProcess.Start);
    
    Thread thread = new Thread(threadStart);
    
    thread.Start();
    

    and then in the event handler:

    private void MyEventHandler(object sender, MyEventArgs e) { 
    ....
    Application.Current.Dispatcher.Invoke(
                    DispatcherPriority.Send,
                    (DispatcherOperationCallback)(arg =>
                    { 
             //do UI updating here ...
            }), null);
    

    I'm not recommending this code, since I'm still trying to understand the WPF thread model, how Dispatcher works, and why in my case the UI wouldn't update until the process was complete even with event handler getting called as expected (by design?). But this has worked for me so far.

    I found these two links helpful:

    http://www.nbdtech.com/blog/archive/2007/08/01/Passing-Wpf-Objects-Between-Threads-With-Source-Code.aspx

    http://srtsolutions.com/blogs/mikewoelmer/archive/2009/04/17/dealing-with-unhandled-exceptions-in-wpf.aspx

提交回复
热议问题