Please give me a hint about the following issue:
ConcurrentBag<string> test = null;
List<string> list= new() { "1", "2", "3", "2", "3", "2", "3", "2", "3", "2",
"3", "2", "3", "2", "3", "2", "3", "2", "3", "2", "3", "2", "3" };
Parallel.ForEach(list, x => { (test ??= new()).Add("result"); });
=> test will have a different value each time when debugging (e. g. 19 / 23 entries)
ConcurrentBag<string> test = new();
List<string> list= new() { "1", "2", "3", "2", "3", "2", "3", "2", "3", "2",
"3", "2", "3", "2", "3", "2", "3", "2", "3", "2", "3", "2", "3" };
Parallel.ForEach(list, x => { (test ??= new()).Add("result"); });
=> test will always have 23 entries
Why does the Parallel.ForEach
not properly add the values when it's instantiated with null
?