4

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

Naveen Chakravarthy
  • 819
  • 2
  • 15
  • 30

2 Answers2

2

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.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
2

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • When I use Timer(System.Timers.Timer it throws an exception. Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. – Naveen Chakravarthy Feb 01 '11 at 23:15
  • 1
    @bonny: Use a WinForms timer. It is already synced to the GUI. – H H Feb 01 '11 at 23:18
  • @Henk. It seems the timer thread is blocked until the Parallel.ForEach is completed. I am using WinForms timer for every 5 sec. The timer is updated only after Parallel.ForEach is completed. I am not able to update the progress to the UI until it Parallel.ForEach finishes processing. – Naveen Chakravarthy Feb 02 '11 at 15:15
  • 1
    @bunny: that could be the case if you run the ForEach from the main thread. You would be blocking your GUI then. Use a Bgw, or create tasks from a regular `foreach` – H H Feb 02 '11 at 15:18
  • @Henk. The application is working like a charm. Thanks a lot. – Naveen Chakravarthy Feb 02 '11 at 16:40