使用 Parallel.ForEach 时如何发送进度
我计划在 DataTable 上使用 Parallel.ForEach ,以便将每条记录写入文件。
我们如何通知用户已处理的记录的百分比/数量。
通常,当我们使用后台工作程序时,我们会有一个 ProgressChanged 事件,其中通知用户已完成工作的百分比。我们如何使用 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要一个从 0 开始的(共享)计数器,并在每个部分的结束处递增(通过互锁)。
然后需要
选项 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
Option 2) is easier and much more efficient when the number of iterations is large.
我也有类似的问题。我们解决这个问题的方法是使用
Interlocked.Increment
位于对所有线程和 UI 可见的数字上,并显示基于该数字的进度条。编辑:
请注意,如果您的计数器是
long
,您将需要使用Interlocked.Read
来阅读它。如果您使用 int,则该过程已经是原子的。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 useInterlocked.Read
to read it. if you are using a int the process is already atomic.