简体   繁体   English

主线程上的任务更新属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM