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.
I.e, will actually access and run foreach
for ALL members of the ConcurrentBag<Τ>
?
ConcurrentBag<Future> futures = new ConcurrentBag<Future>();
foreach (var 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.