在 parallel.foreach 范围之外增加一个计数值 [英] increment a count value outside parallel.foreach scope

查看:25
本文介绍了在 parallel.foreach 范围之外增加一个计数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 parallel.foreach 循环范围之外增加整数值?同步访问并行循环外的对象的最简单方法是什么?

How can I increment an integer value outside the scope of a parallel.foreach loop? What's is the lightest way to synchronize access to objects outside parallel loops?

var count = 0;
Parallel.ForEach(collection, item =>
{
  action(item);
  // increment count??
}

推荐答案

我喜欢打死马!:)

从多个线程增加计数的最轻量"方法是:

The "lightest" way to increment the count from multiple threads is:

Interlocked.Increment(ref count);

但正如其他人指出的那样:如果您在 Parallel.ForEach 中执行此操作,那么您可能做错了.

But as others have pointed out: if you're doing it inside Parallel.ForEach then you're probably doing something wrong.

我怀疑由于某种原因您正在使用 ForEach 但您需要一个正在处理的项目的索引(它永远不会与 Parallel.ForEach).我很亲近吗?为什么需要计数?你想施展什么样的 VooDoo 魔法?

I'm suspecting that for some reason you're using ForEach but you need an index to the item you're processing (it will never work with Parallel.ForEach). Am I close? Why do you need the count? What sort of VooDoo magic are you trying to do?

如果您的键是 URI 并且值为 TAnswer,那么您似乎对 ConcurrentDictionary 是安全的.只要您不尝试使用计数来引用集合中的元素,我就不会看到问题.

You seem to be safe with the ConcurrentDictionary if your key is the URI and the value is TAnswer. I don't see a problem as long as you don't try to use the count to reference elements in your collection.

如果您需要计数器,请使用 Parallel.For 循环...它可以安全地为您增加计数器.

If you need a counter, then use the Parallel.For loop... it safely increments the counter for you.

这篇关于在 parallel.foreach 范围之外增加一个计数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆