Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track progress when using Parallel.ForEach

I am refactoring my program to use Parallel.ForEach. Before, when I was using a regular for loop, I was updating a WPF progress bar using Dispatcher, displaying the % completed by dividing the current array index by the array size. With a parallel foreach loop this does not display properly i.e. % jumps eratically, which is expected.

How can I update a WPF progress bar from a parallel for each loop so I can track the number of completed iterations?

like image 615
Vince Avatar asked Oct 06 '10 01:10

Vince


1 Answers

As SLaks suggests, you should just increment the progress bar value instead of setting it to the current index that you got from the Parallel.For method.

However, I would seriously consider using some less expensive way than sending a message to the UI thread with every iteration. If you have a large number of iterations, then sending a message with every iteration could be quite demanding. You could declare a local variable count and use Interlocked.Increment to increment the variable safely in the body of the parallelized loop.

  • Then you could use something like if (count % 10 == 0) // ... to update the GUI only after 10 iterations. (This is not fully correct, as other threads may update the count before you check, but if it is just for the purpose of GUI notificiation, then it shouldn't matter - you definitely don't want to use lock in the loop body).

  • Alternatively, you could create a Timer that would repeatedly check the value of count from the GUI thread and update the progress bar. This is perhaps even easier and you can guarantee that the progress bar will be updated enough often, but not more.

like image 137
Tomas Petricek Avatar answered Oct 03 '22 16:10

Tomas Petricek