From 2fb51601eb79933f8fd2d2ed284c3981776646e3 Mon Sep 17 00:00:00 2001 From: Code Maze Date: Fri, 4 Dec 2026 18:26:43 +0100 Subject: [PATCH] Lock the list in RemoveFromConcurrentBagConcurrently List is not thread-safe, so calling numbersList.Add from the Parallel.For iterations could lose items. Only the Add call is now inside lock (numbersList); TryTake stays outside the lock, so the method still shows concurrent removal from the bag. Matches the current code in https://code-maze.com/csharp-concurrentbag/ --- .../ConcurrentBagInCSharp/ConcurrentBagDemo.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/collections-csharp/ConcurrentBagInCSharp/ConcurrentBagInCSharp/ConcurrentBagDemo.cs b/collections-csharp/ConcurrentBagInCSharp/ConcurrentBagInCSharp/ConcurrentBagDemo.cs index 3eedaecb6c..2d38878248 100644 --- a/collections-csharp/ConcurrentBagInCSharp/ConcurrentBagInCSharp/ConcurrentBagDemo.cs +++ b/collections-csharp/ConcurrentBagInCSharp/ConcurrentBagInCSharp/ConcurrentBagDemo.cs @@ -52,7 +52,10 @@ public static List RemoveFromConcurrentBagConcurrently(ConcurrentBag b if (bag.TryTake(out int number)) { Console.WriteLine($"Thread {Environment.CurrentManagedThreadId} took item: {number}"); - numbersList.Add(number); + lock (numbersList) + { + numbersList.Add(number); + } } });