Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a real world use for ConcurrentBag<T>?

A ConcurrentBag will allow multiple threads to add and remove items from the bag. It is possible that a thread will add an item to the bag and then end up taking that same item right back out. It says that the ConcurrentBag is unordered, but how unordered is it? On a single thread, the bag acts like a Stack. Does unordered mean "not like a linked list"?

What is a real world use for ConcurrentBag?

like image 802
Dustin Davis Avatar asked Jun 22 '11 22:06

Dustin Davis


People also ask

When use ConcurrentBag?

The ConcurrentBag is one of the thread safe collections that was introduced in . NET 4.0. This collection allows us to store objects in an unordered manner and allows for duplicates. It is useful in a scenario where we do not need to worry about the order in which we would retrieve the objects from the collection.

How does Concurrent bag work?

ConcurrentBag allows you to store objects in unordered way. Contrary to ConcurrentDictionary class, it allows you to store duplicate objects. ConcurrentBag allows multiple threads to store the objects. It is optimized for scenarios where same thread act as producer and consumer.

How do I add a list in ConcurrentBag?

ConcurrentBag<int> ccBag = new ConcurrentBag<int>(); var listOfThings = new List<int>() { 1, 2, 4, 5, 6, 7, 8, 9 }; ccBag. AddRange(listOfThings);


1 Answers

Because there is no ordering the ConcurrentBag has a performance advantage over ConcurrentStack/Queue. It is implemented by Microsoft as local thread storage. So every thread that adds items does this in it's own space. When retrieving items they come from the local storage. Only when that is empty the thread steals item from another threads storage. So instead of a simple list a ConcurrentBag is a distributed list of items. And is almost lockfree and should scale better with high concurrency.

Unfortunately in .NET 4.0 there was a performance issue (fixed in 4.5) see http://ayende.com/blog/156097/the-high-cost-of-concurrentbag-in-net-4-0

like image 103
IvoTops Avatar answered Oct 24 '22 16:10

IvoTops