【发布时间】:2016-02-19 10:33:28
【问题描述】:
我确实有一个 WPF 应用程序实时显示数据(从另一个线程计算)。但是我的 UI 组件(这里是 TextBlock)更新非常缓慢。
我使用带有PropertyChanged 通知的传统数据绑定。
xml:
<TextBlock
Foreground="DarkGray"
Text="{Binding Path=ContactSurface, StringFormat='{}{0:0.00} cm²'}"/>
代码隐藏(不,这不是 MVVM,真丢脸):
private double _contactSurface;
public double ContactSurface
{
get { return _contactSurface; }
set { _contactSurface = value; RaisePropertyChanged("ContactSurface"); }
}
public void Compute() // external thread about 10 Hz
{
ContactSurface = (double)nbSensorsNotNulls * DataSource.SensorSurface * 0.01;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { })); // does not change a thing
//Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { })); // crash : Cannot perform this operation while dispatcher processing is suspended.
//UpdateLayout(); // crash : The calling thread can not access this object because a different thread owns it
//InvalidateVisual(); // crash : The calling thread can not access this object because a different thread owns it
}
我在Compute() 结尾处尝试了一些我在网络上找到的东西,结果非常简单
【问题讨论】:
-
也许你应该把 ContactSurface = (double)nbSensorsNotNulls * DataSource.SensorSurface * 0.01 放入 Dispatcher.BeginInvoke
-
这似乎行得通!我不确定是什么问题。也许 RaisePropertyChanged() 没有从 Compute 线程同步,所以调度程序不知道 ContactSurface 发生了变化。非常感谢!!!
-
这种方法有一个不便之处:它往往会冻结 UI。我正在努力。
标签: wpf multithreading data-binding