问题
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}"/>
回答1:
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.
回答2:
Binding to single properties is not thread affine. You can do this without problems, the binding will do the necessary for you.
However take care, this is only for single property bindings. If you have for example an ObservableCollection, you can not add or remove items from another thread, even if the collection is bound through binding!
来源:https://stackoverflow.com/questions/7999344/task-parallel-library-inotifypropertychanged-not-throwing-an-exception