I have a wpf project where I am using INotifyPropertyChanged on a property which binds to the textbox. I am updating this value on a different thread using task (TaskParallelLibrary). It is updated properly and does NOT throw an exception. I was thinking it would throw an exception because it is running on a background thread and not UI thread. Ofcourse it is throwing an exception if I directly use the UI element. So, does INotifyPropertyChanged bind mechanism takes care of dispatching to the UI thread automatically?
Here is my code with the property.
private string _textProperty = "";
public string TextProperty
{
get
{
return _textProperty;
}
set
{
if (_textProperty != value)
{
_textProperty = value;
NotifyPropertyChanged("TextProperty");
}
}
}
and my task creation is
var task = new Task(() =>
{
TextProperty = "ABCD"; // Works.
// txtBox.Text = "ABCD"; // Throws an exception.
});
task.Start();
and the textbox in XAML is <TextBox Name="txtBox" Text="{Binding TextProperty}"/>
I was thinking it would throw an exception because it is running on a background thread and not UI thread.
WPF allows you to set a bound value on a background thread. It will handle the marshaling to the UI thread for you.
Be aware, however, that this does not work for elements of a collection. If you want to add to an ObservableCollection<T>
which is bound, for example, you'll have to marshal back to the UI thread. There are various workarounds, however, which can ease this if required. Note that this behavior changes in WPF 4.5, which will simplify multithreaded development in WPF in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With