[英]Task updating properties on Main thread
I am trying to update property on my main Thread, which is bind to ProgressBar. 我正在尝试更新绑定到ProgressBar的主线程上的属性。 In viewmodel I have the bellow code, which is not working.
在视图模型中,我有下面的代码,它不起作用。
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task task = Task.Factory.StartNew(() =>
{
DoLongRunningWork();
}).ContinueWith(_=>
{
ApplicationStatus = "Task finished!";
}, TaskScheduler.FromCurrentSynchronizationContext());
DoLongRunningWork()
{
// Alot of stuff
Task.Factory.StartNew(() =>
{
ProgressBarValue += progressTick;
}).Start(uiScheduler);
}
If the property ProgressBarValue
is bound to a WPF element, then the only thread that can update the ProgressBar
is the very thread that created it. 如果属性
ProgressBarValue
绑定到WPF元素,则唯一可以更新ProgressBar
的线程就是创建它的线程。
So, my assumption is that the class that contains ProgressBarValue
also implements INotifyPropertyChanged
. 因此,我的假设是包含
ProgressBarValue
的类也实现INotifyPropertyChanged
。 This means that you have some logic that raises the event PropertyChanged
. 这意味着您具有引发事件
PropertyChanged
某些逻辑。
I would create a method that raises the event, and always does so using the Dispatcher
. 我将创建一个引发事件的方法,并始终使用
Dispatcher
。 (The Dispatcher
allows you to call functions on the thread that created your WPF controls.) (
Dispatcher
允许您在创建WPF控件的线程上调用函数。)
private void raisePropertyChanged(string name)
{
Dispatcher.InvokeAsync(()=>
{
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
});
}
This will always update the ProgressBar
on the proper thread. 这将始终在适当的线程上更新
ProgressBar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.