Skip to content

ConcurrentBag in C#: lock the list when collecting taken items - #2458

Merged
vladimir-pecanac-main merged 1 commit into
mainfrom
concurrentbag-lock-list-add
Dec 4, 2026
Merged

vladimir-pecanac-main merged 1 commit into
mainfrom
concurrentbag-lock-list-add

Conversation

@vladimir-pecanac-main

Copy link
Copy Markdown
Collaborator

RemoveFromConcurrentBagConcurrently called numbersList.Add(number) from the Parallel.For iterations with no lock. List<T> is not thread-safe, so items taken from the bag could go missing from the list.

Only the Add call now sits inside lock (numbersList). TryTake stays outside the lock, so the method still shows several threads taking from the bag at once. The method matches code block 4 in the article: https://code-maze.com/csharp-concurrentbag/

The folder builds with no warnings and all 10 tests pass locally. Over 20 runs, the method returned 20 distinct items each time.

List<T> 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/
@vladimir-pecanac-main
vladimir-pecanac-main merged commit 4c25ef7 into main Dec 4, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants