I am trying to update property on my main Thread, which is bind to 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.

So, my assumption is that the class that contains ProgressBarValue also implements INotifyPropertyChanged. This means that you have some logic that raises the event PropertyChanged.

I would create a method that raises the event, and always does so using the Dispatcher. (The Dispatcher allows you to call functions on the thread that created your WPF controls.)

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top