In a parallel section of my code, I save the results from each thread to a ConcurrentBag. However, when this is complete, I need to iterate through each of these results and run them through my evaluation algorithm. Will a normal foreach actually iterate through all members, or do I need special code? I've also thought about using something like a queue instead of a bag, but I don't know which would be best. The bag will typically contain only 20 or so items at the end of the parallel code.
ie, will actually access and run foreach for ALL members of the ConcurrentBag?
ConcurrentBag futures = new ConcurrentBag();
foreach(move in futures)
{
// stuff
}
You don't need special code, the C#'s foreach will call "GetEnumerator" which gives you a snapshot:
The items enumerated represent a moment-in-time snapshot of the contents of the bag. It does not reflect any update to the collection after GetEnumerator was called.
You can use normal ForEach on ConcurrentBag, but it wont produce any performance impact.
This is similar like using ForEach on List.
For better performace use Parallel.Foreach on ConcurrentBag.
Parallel.ForEach(futures,move=> doOperation;);
Use ConcurrentBag, only if u want to perform multithreaded operations.
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