Search code examples
wpfmultithreadingbusyindicator

Display busyindicator in wpf application


I have a BusyIndicator from the wpf extended toolkit and I'm running a function that takes a while to complete. If I run the time consuming task in a separate thread, I get a NotSupportedException because I'm attemping to insert objects into an ObservableCollection from that different thread. I don't really want to spend a lot of time refactoring the code, if possible... Is there a way that I can set the visibility of the indicator in a separate thread instead?

EDIT

ThreadStart start = delegate()
  {
      System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
          {
              IsBusy = true;
          }));
   };

new Thread(start).Start();                                
longRunningFunction();

This did not work for me either.


Solution

  • You should be able to use the Dispatcher for things like that. e.g.

    Application.Current.Dispatcher.Invoke((Action)(() =>
    {
        _indicator.Visibility = Visibility.Visible;
    }));
    

    This will cause the code to be run on the UI-Thread.

    There is more info (including how to "properly" do this, with CheckAccess and such) on it in the threading model reference.