Question

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);
}

No correct solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top