开发者

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜