Trae Moore
Trae Moore

Reputation: 1787

Update UI Thread from ViewModel

I am trying to execute the simple action of updating a progress bar on my UI inside of a loop by using a BackgroundWorker. I don't know what I'm doing wrong. Any help is greatly appreciated.

private void ProcessButtonClickAction(object param)
{
   BackgroundWorker BGWUpdateUi = new BackgroundWorker();

   BGWUpdateUi.ProgressChanged += (sender, args) =>
   {
       ProgressBarValue += args.ProgressPercentage;
       ((SelectedDwgFile)args.UserState).Status = "Completed";
   };

   BGWUpdateUi.WorkerReportsProgress = true;

    foreach(var obj in FileList)
    {
        Thread.Sleep(250);
        BGWUpdateUi.ReportProgress(pbvalueIncrement, obj);
    }
}

The collection is an ObservableCollection and ProgressBarValue is bound to the value of the progress bar.

I have looked at several of examples and no matter which one I try - BackgroundWorker, Dispatcher - they all update after the loop.

Upvotes: 1

Views: 1400

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

Put the part that you want to run in the background, into the DoWork method, and then call RunWorkerAsync:

private void ProcessButtonClickAction(object param)
{
   BackgroundWorker BGWUpdateUi = new BackgroundWorker()

   BGWUpdateUi.DoWork += (sender, args) =>
   {
       foreach (var obj in FileList)
       {
           Thread.Sleep(250);
           obj.Status = "Completed";
           ProgressBarValue += pbvalueIncrement;
       }
   };
   BGWUpdateUi.RunWorkerAsync();
}

Also, make sure to dispatch UI-related updates back to the UI thread (otherwise you will get a cross-thread access exception).

Upvotes: 3

Related Questions