I am running some code that uses ConcurrentBags. I am exploring the IEnumerable functionality. The code I run is
ConcurrentBag<int> bag = new ConcurrentBag<int>();
Task.Run(() =>
{
bag.Add(42);
Thread.Sleep(1000);
bag.Add(21);
});
Task.Run(() =>
{
foreach (int i in bag)
Console.WriteLine(i);
}).Wait();
I expected the code to return 42, but it is returning nothing. Was my assumption wrong?
You have a race condition, basically. On my machine, this does print 42 most of the time - but fundamentally you have two independent tasks: one adding, and one printing. There is no guarantee which task will execute its first statement first, as you have no synchronization or coordination between the two tasks.
If you want to ensure that the first Add
call has completed before you start to iterate over the bag, you'll need to have some coordination.
See more on this question at Stackoverflow