任务并行库INotifyPropertyChanged是否不会引发异常? [英] Task parallel library INotifyPropertyChanged NOT throwing an exception?

查看:69
本文介绍了任务并行库INotifyPropertyChanged是否不会引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个wpf项目,其中我在绑定到文本框的属性上使用INotifyPropertyChanged.我正在使用任务(TaskParallelLibrary)在其他线程上更新此值.它已正确更新,不会引发异常.我以为它会引发异常,因为它在后台线程而不是UI线程上运行.当然,如果我直接使用UI元素,它将引发异常.那么,INotifyPropertyChanged绑定机制是否负责自动分派到UI线程?

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");
            }
        }
    }

我的任务创建是

var task = new Task(() =>
        {
            TextProperty = "ABCD"; // Works.
            // txtBox.Text = "ABCD"; // Throws an exception.
        });
        task.Start();

,XAML中的文本框为< TextBox Name ="txtBox" Text ="{Binding TextProperty}"/>

and the textbox in XAML is <TextBox Name="txtBox" Text="{Binding TextProperty}"/>

推荐答案

我当时以为它会引发异常,因为它在后台线程而不是UI线程上运行.

I was thinking it would throw an exception because it is running on a background thread and not UI thread.

WPF允许您在后台线程上设置绑定值.它将为您处理到UI线程的封送处理.

WPF allows you to set a bound value on a background thread. It will handle the marshaling to the UI thread for you.

但是请注意,这对于集合的元素确实不起作用.例如,如果要添加到绑定的 ObservableCollection< T> ,则必须将其编组回UI线程.有各种解决方法,但是,如果需要,可以减轻这种情况.请注意,在WPF 4.5中此行为更改了,它将在将来简化WPF中的多线程开发.

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.

这篇关于任务并行库INotifyPropertyChanged是否不会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆