I cannot understand if it is mandatory to use Dispatcher to notify UI thread that a bound property has been updated by a non-UI thread.
Starting from a basic example, why is the following code not throwing the famous (I remember struggling on this in past coding experiences) The calling thread cannot access this object because a different thread owns it exception?
private int _myBoundProperty;
public int MyBoundProperty { get { return _myBoundProperty; } set { _myBoundProperty = value; OnPropertyChanged(); } }
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void Test()
{
new System.Threading.Thread(() =>
{
try
{
MyBoundProperty += DateTime.Now.Second;
}
catch(Exception ex)
{
}
}).Start();
}
<TextBlock Text="{Binding MyBoundProperty"/>
I saw some posts on this topic, but they seem to me quite confusing:
- someone stating Dispatcher is required for collections but not for single variables: so why this other example still not throwing exception?
private ObservableCollection<int> _myBoundPropertyCollection;
public ObservableCollection<int> MyBoundPropertyCollection { get { return _myBoundPropertyCollection; } set { _myBoundPropertyCollection = value; OnPropertyChanged(); } }
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void TestCollection()
{
new System.Threading.Thread(() =>
{
try
{
//MyBoundPropertyCollection = new ObservableCollection() { 0 }; //even so not throwing
MyBoundPropertyCollection[0] += DateTime.Now.Second;
}
catch(Exception ex)
{
}
}).Start();
}
<TextBlock Text="{Binding MyBoundPropertyCollection[0]"/>
- someone stating it was something required by previous .NET versions: so now can we removed those Dispatcher calls (I am using .NET Framework 4.7)?
- someone stating it is a good practice to use Dispatcher even if your code does not throw exception: seems like an act of faith...