-1

I have a method getPlugins that takes quite a long time to run. Essentially it's parsing a very large log file. I know the log file goes from time 0 to time 24. I would like to update a ProgressBar based on the current time. Here's the structure of my code, but the bar only seems to be updated once my loop is finished... How can I fix this?

private void getPlugins(String filePath)
{
     var w = new Window2();
     w.Show();
     w.progress.Value = 0;

     List<String> pluginNames = new List<String>();

     string strLine;

     // Read the file and display it line by line.
     System.IO.StreamReader file = new System.IO.StreamReader(filePath);

      while ((strLine = file.ReadLine()) != null)
      {
          // Do stuff....

          float time; // Here I have time as a float from 0 to 24
          w.progress.Value = time;
      }

      file.Close();
      w.progress.Value = 24;
      w.Close();
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
TurtleFan
  • 289
  • 2
  • 17
  • 2
    The reason this is happening is because your trying to update it and process the file on the UI thread. You need to create a thread to process the file and then see the following on how to update the progress bar http://stackoverflow.com/questions/6036279/wpf-progress-bar-update-with-dispatcher – 3dd Sep 01 '15 at 05:18
  • 1
    See this [link](http://stackoverflow.com/questions/12676490/progress-bar-not-progressing) and [this](http://www.dotnetcurry.com/ShowArticle.aspx?ID=571) for dispatcher and background worker. – Kryptonian Sep 01 '15 at 05:19
  • http://stackoverflow.com/questions/6365887/can-you-link-to-a-good-example-of-using-backgroundworker-without-placing-it-on-a/6365951#6365951 – CharithJ Sep 01 '15 at 05:21

1 Answers1

3

Basically the idea is that you can not update UI elements directly from a non UI thread. WPF has a Dispatcher class that gives u access to UI elements and using this you can update the UI elements like below code

Application.Current.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, (Action)(() =>
                    {
                        w.progress.Value = time;
                    }));
WAQ
  • 2,556
  • 6
  • 45
  • 86