Home > Net >  Updating progressbar created on different thread
Updating progressbar created on different thread

Time:07-28

I am currently trying to update a progress bar that is defined in another window that is created by a different thread.

I need to send progress updates from the main thread in order to have the correct value displayed on progress bar.

Any help is appreciated, thanks in advance. Below is the code:

  private void StartLoadingWindow(object sender, RoutedEventArgs e)
  {
     var t = new Thread(ThreadLoadingWindow); 
     t.SetApartmentState(ApartmentState.STA); //Mandatory
     t.Start();
  }

  private void ThreadLoadingWindow()
  {
     var w = new LoadingWindowsControl();
     w.Closed  = (sender, args) =>
     {
        //Exit Dispatcher when Window closes
        Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.SystemIdle);
        Dispatcher.Run();
     };
     w.ShowDialog();
  }

Inside the LoadingWindowsControl I have created a simple mvvm progress bar.

CodePudding user response:

The typical way would be to use a Progress<T> object. If this is created on the UI thread it will invoke the ProgressChanged on the UI thread. Attach an event handler to this that updated your progress bar.

It looks however like you are creating multiple UI threads, and this is probably not a good idea. If you want to do something in the background you should use Task.Run, await the result, and update the UI. If you need continuous update you should follow the Progress<T> example. Create an object that you inform of the updates, and let it post the update work to the the UI thread.

  • Related