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 execution of Parallel. Foreach is faster than normal ForEach.
For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration.
No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.
ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.
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?
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.
If you need a counter, then use the Parallel.For
loop... it safely increments the counter for you.
Use Interlocked.Increment method in this way.
int count = 0; Parallel.ForEach(users, (u) => { var currentCount = Interlocked.Increment(ref count); Log(String.Format("Step {0} of {1}", currentCount, users.Count)); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With