gpt4 book ai didi

wpf - 从另一个线程更快地刷新 TextBlock

转载 作者:行者123 更新时间:2023-12-03 12:59:54 25 4
gpt4 key购买 nike

我确实有一个 WPF 应用程序实时显示数据(从另一个线程计算)。但是我的 UI 组件(这里是 TextBlock)更新非常缓慢。
我使用传统的数据绑定(bind) 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() 结尾时在网络上找到的东西非常平均的结果细节

最佳答案

如果您在另一个线程中执行一些耗时的工作,那么您 必须将另一个线程的结果与 UI 线程同步。同步两个线程(新线程和UI线程),需要使用 Dispatcher .

As MSDN says:

Only one thread can modify the UI thread. But how do background threads interact with the user? A background thread can ask the UI thread to perform an operation on its behalf. It does this by registering a work item with the Dispatcher of the UI thread. The Dispatcher class provides two methods for registering work items: Invoke and BeginInvoke. Both methods schedule a delegate for execution. Invoke is a synchronous call – that is, it doesn’t return until the UI thread actually finishes executing the delegate. BeginInvoke is asynchronous and returns immediately.



例如:
Task.Run(()=> {
var result = (double)nbSensorsNotNulls * DataSource.SensorSurface * 0.01;
Thread.Sleep(5000);//imitate time consuming work
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render,
new Action(() => {
ContactSurface=result;}));
});

在上面的示例中,我们创建了一个新线程( Task.Run(...))并将新线程的结果与 UI 线程( Dispatcher.BeginInvoke(...))同步

关于wpf - 从另一个线程更快地刷新 TextBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35503109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com