Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task parallel library INotifyPropertyChanged NOT throwing an exception?

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}"/>

like image 352
Jonna Avatar asked Nov 03 '11 17:11

Jonna


1 Answers

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.

like image 126
Reed Copsey Avatar answered Sep 27 '22 02:09

Reed Copsey