How to send progress when using Parallel.ForEach

I plan to use Parallel.ForEach in a DataTable so that every record can be written to a file.

How can we notify the user about the percentage / number of processed records.

Usually, when we use Background worker, we have a ProgressChanged event in which the user is notified of the percentage of work completed. How can we achieve this using Parallel.ForEach tasks or several?

Thanks Bunny

+4
source share
2 answers

You will need a counter (total) that starts at 0 and that you increase (with a lock) at the end of each part.

And then you need

  • raises an event and the event should use Invoke (or Dispatch)
  • or periodically the timer selects the counter

Option 2) is simpler and more efficient when the number of iterations is large.

+2
source

I had a similar problem. What we did to solve it was to use the Interlocked.Increment number, which was visible to all threads and the user interface, and displayed a progress bar based on this.

EDIT: note that if you use your long counter, you will need to use Interlocked.Read to read it. if you use int, the process is already atomic.

+2
source

Source: https://habr.com/ru/post/1338012/


All Articles