-1

I have made an application in WPF where I am making a long conversion process. so I wanted to put progress bar window, so i have used BusyIndicator progress bar from wpftoolkit dll and trying to show when my conversion will start. But when I click on Conversion button it showing exception - "the calling thread cannot access this object because a different thread owns it"...

My Code -

private void ConvertBtn_OnClick(object sender, RoutedEventArgs e)
{     
  Task.Factory.StartNew(() =>
  {
    ConversionToExcel();//My conversion methode
    for (int i = 0; i < 10; i++)
    {
      Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
        () => { ProgressIndicator.BusyContent = string.Format("Inprogress, please wait..."); }
      ));
      Thread.Sleep(1000);
    }
  }).ContinueWith((task) => { ProgressIndicator.IsBusy = false; }, TaskScheduler.FromCurrentSynchronizationContext()
  );
}
  • 1
    Possible duplicate of [The calling thread cannot access this object because a different thread owns it](https://stackoverflow.com/questions/9732709/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it) – FCin Sep 04 '18 at 12:40

1 Answers1

0

Set IsBusy=true before starting new thread.

private void ConvertBtn_OnClick(object sender, RoutedEventArgs e)
{    
  ProgressIndicator.BusyContent = string.Format("Inprogress, please wait..."); 
  Task.Factory.StartNew(() =>
  {
    ConversionToExcel();//My conversion method

  }).ContinueWith((task) => { ProgressIndicator.IsBusy = false; }, TaskScheduler.FromCurrentSynchronizationContext()
  );
}

Also, I think you should have your own IsBusy property and bind it to ProgressIndicator.IsBusy in XAML.

Krzysztof Skowronek
  • 2,796
  • 1
  • 13
  • 29