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:
But as others have pointed out: if you’re doing it inside
Parallel.ForEachthen you’re probably doing something wrong.I’m suspecting that for some reason you’re using
ForEachbut you need an index to the item you’re processing (it will never work withParallel.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
ConcurrentDictionaryif your key is theURIand the value isTAnswer. 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.Forloop… it safely increments the counter for you.