增加外parallel.foreach范围计数值 [英] increment a count value outside parallel.foreach scope
问题描述
我怎样才能增加一个parallel.foreach环路范围之外的整数值?什么是访问对象以外的并行循环同步最轻的方式?
VAR计数= 0;
Parallel.ForEach(收集,项目= GT;
{
行动项目);
//增量计数?
}
我喜欢击败死马! :)
在最轻的方式,从多个线程递增计数:
Interlocked.Increment(引用计数);
但正如其他人指出:如果你这样做是在 Parallel.ForEach
那么你可能做错事
我怀疑,由于某种原因你使用的ForEach
但是你需要一个索引,你正在处理的项目(它不会与<$ C工作$ C> Parallel.ForEach )。我是否关闭?为什么你需要计数?什么样的巫术,你想干什么?
更新:
您似乎与安全的 ConcurrentDictionary
如果你的关键是 URI
和值 TAnswer
。我没有看到一个问题,只要你不尝试使用计数来引用元素的收藏。
最后...
如果你需要一个柜台,然后使用的Parallel.For
环......它安全地递增计数器为您服务。
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??
}
I like to beat dead horses! :)
The "lightest" way to increment the count from multiple threads is:
Interlocked.Increment(ref count);
But as others have pointed out: if you're doing it inside Parallel.ForEach
then you're probably doing something wrong.
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?
UPDATE:
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.
Finally...
If you need a counter, then use the Parallel.For
loop... it safely increments the counter for you.
这篇关于增加外parallel.foreach范围计数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!