Thread safety, lists, binding and WPF

后端 未结 2 927
慢半拍i
慢半拍i 2021-01-17 04:02

I have a WPF ListView that is bound to a collection (List). It is currently updated from the current thread which works ok.

I want to move the

相关标签:
2条回答
  • 2021-01-17 04:22

    You can make the collection update from Dispatcher.Invoke to avoid those threading problems:

    void ThreadProc()
    {
       window.Dispatcher.Invoke(() => {
          //UpdateList
       });
    }
    
    0 讨论(0)
  • 2021-01-17 04:26

    INotifyPropertyChanged is not thread safe, and it does block the calling thread.

    Best? That's A good question. I dunno. The bottom line is that, at some time or another, calls must be marshalled onto the UI thread. When do you do this?

    You could 1) prepare everything, then deliver it to the UI thread where the UI is then updated. Or, you could 2) implement INotifyPropertyChanged and make the firing of that event always happen on the UI thread, or 3) you could do one of a number of different things.

    Usually, however, you would want updates to the UI to happen all at once (not one at a time, as you would get when adding single items to an ObservableCollection, for instance). So it might be advisable to make some thread safe base classes that implement INotifyProperty and CollectionChanged and use these.

    There is nothing in the framework that will do this for you, unfortunately.

    0 讨论(0)
提交回复
热议问题