Let's say you have a non synchronized list:
List<string> somelist = new List<string>();
Now from multiple threads you add to this list:
List<ProcessItem> processItems = new List<ProcessItem>();
// Create some items in process items
Parallel.ForEach(processItems, (nextProcessItem) => {
somelist.Add(nextProcessItem.Id)
});
Now we try to use this list in another call:
Parallel.ForEach(somelist, (nextListItem) => {
// Intermittently some nextListItem are coming in null
Console.Write(nextListItem);
});
What is the expected result? I'm trying to debug a client's program and I noticed they were doing something just like this scenario. And the result was certain entries in somelist
were actually null
intermittently.
I changed them to ConcurrentQueue
instead hoping it solves the issue.
Is that the expected behavior one would see from adding to a non-synchronized list in multiple threads?