Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a normal foreach on a ConcurrentBag?

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
}
like image 514
furrysalamander Avatar asked Feb 08 '16 06:02

furrysalamander


2 Answers

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.

like image 105
Daniel James Bryars Avatar answered Nov 10 '22 08:11

Daniel James Bryars


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.

like image 1
Nambirajan S Avatar answered Nov 10 '22 10:11

Nambirajan S