The Bound view property property has been updated in the background thread; Will the user interface always see the updated value?

If I have some (non-volatile) data bound to the user interface via a view model and I update this data from the background thread without blocking anything and fire the PropertyChanged event, will I guarantee that the user interface will see this update? If so, why?

I see that CLRBindingWorker calls Dispatcher.BeginInvoke and thus ensures that the property is read from the user interface stream. I want to know if the property value will always be β€œfresh” in the user interface thread (for example, a script similar to http://www.yoda.arachsys.com/csharp/threads/volatility.shtml can happen).

A previous answer suggested that this is true, but without any explanation.

Example:

 public class MyViewModel : INotifyPropertyChanged { // Bound to the view as <TextBlock Text="{Binding Data}" /> private long _data; public long Data { get { return _data; } set { _data = value; FirePropertyChanged("Data"); } } public MyViewModel() { new Thread(Updater).Start(); } private void Updater() { while (true) { Data++; Thread.Sleep(1000); } } private void FirePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } 
+6
multithreading c # memory-model wpf
source share
3 answers

Here are my comments

1) Since there is only 1 thread in the pump message, you do not need to worry about full or partial fences, and the volatile keyword has no effect.

2) INotifyPropertyChanged refers to events, and if one delegate in the list of event calls fails, the rest will not be called because the effect will not be updated.

3) If you use nested pump messages (for example, modal windows), then the child manager can update your property to the parent manager, thereby making the update unsynchronized with the expected one.

4) if you use IValueConverter and the conversion fails, your property will not be updated.

5) If you use explicit update triggers in your bindings, this can have an effect (depending on your scenario)

+1
source share

No, this is not in all cases. To ensure that your UI updates, you should always update the associated values ​​in the UI thread using Dispatcher .

0
source share

All Articles