Silverlight DataBinding跨线程问题
时间:2020-03-05 18:48:33 来源:igfitidea点击:
我有一个Image控件,它的源绑定到对象的属性(图像的字符串url)。进行服务呼叫后,我使用新的URL更新数据对象。调用PropertyChanged事件后,该异常在离开我的代码后引发。
数据结构和服务逻辑都是在不了解UI的核心dll中完成的。无法访问分派器时如何与UI线程同步?
PS:为了获得Dispatcher而访问Application.Current.RootVisual并不是解决方案,因为root视觉位于不同的线程上(这是我需要避免的确切异常)。
PPS:这仅是图像控件的问题,绑定到任何其他ui元素,交叉线程问题已为我们处理。
解决方案
回答
我们是否尝试实现INotifyPropertyChanged?
回答
Application类上RootVisual的属性getter具有导致该异常的线程检查。通过在我的App.xaml.cs中的我自己的属性中存储根可视对象的调度程序来解决此问题:
public static Dispatcher RootVisualDispatcher { get; set; } private void Application_Startup(object sender, StartupEventArgs e) { this.RootVisual = new Page(); RootVisualDispatcher = RootVisual.Dispatcher; }
如果然后在App.RootVisualDispatcher而不是Application.Current.RootVisual.Dispatcher上调用BeginInvoke,则不应获取此异常。
回答
我遇到了与此类似的问题,但这是在Windows窗体中:
我有一个具有自己的线程的类,用于更新有关另一个进程的统计信息,我的UI中有一个控件绑定到该对象。我遇到了跨线程调用问题,这是我如何解决的问题:
Form m_MainWindow; //Reference to the main window of my application protected virtual void OnPropertyChanged(string propertyName) { if(PropertyChanged != null) if(m_MainWindow.InvokeRequired) m_MainWindow.Invoke( PropertyChanged, this, new PropertyChangedEventArgs(propertyName); else PropertyChanged(this, new PropertyChangedEventArgs(propertyName); }
这似乎很好用,如果有人提出建议,请告诉我。
回答
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});
也看这里。