Naveen Chakravarthy
Naveen Chakravarthy

Reputation: 839

How to send the progress when using Parallel.ForEach

I am planning to use Parallel.ForEach on a DataTable so that each record can be written to a file.

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

Normally when we use Background worker we have a ProgressChanged event where the user is notified on the percentage of work done. How can we achieve this using Parallel.ForEach or Multiple tasks?

Thanks, Bunny

Upvotes: 4

Views: 3149

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273244

You will need a (shared) counter that starts at 0 and that you increment (with Interlocked) at the end of each part.

And then you need to

  1. trigger an event, and the event has to use Invoke (or Dispatch)
  2. or have a Timer periodically sample the counter

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

Upvotes: 2

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

I have had a similar issue. What we did to solve it was to use Interlocked.Increment on a number that was visible to all the threads and the UI and shown the progress bar based off of that.

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

Upvotes: 2

Related Questions