Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what circumstances can ConcurrentBag.TryTake() fail?

I'm thinking of using a ConcurrentBag in a program I'm writing, however I can't seem to find enough documentation on TryTake.

I understand that the method might fail, but I can't find an explanation of the cases in which such failure might happen, and what state the collection will be left in after the failure.

If it's only in the case of another thread having already removed the item then I don't care, but what I can't really afford is the item I want to remove to still be in the collection after the call.

Can this ever be the case?

like image 374
em70 Avatar asked Jan 06 '11 10:01

em70


People also ask

Is ConcurrentBag thread safe?

ConcurrentBag<T> is a thread-safe bag implementation, optimized for scenarios where the same thread will be both producing and consuming data stored in the bag.

How do I remove a concurrent bag?

TryTake(out T) - This method is used to retrieve an element from ConcurrentBag<T>. Note that this method removes the item from the collection.

How does concurrent bag work?

ConcurrentBag maintains a local queue for each thread that access it, and when the same thread is retrieving items, it gives priority to those items that are in same thread queue. ConcurrentBag is an implementation of Work stealing algorithm. You can read more about work stealing algorithm here.


1 Answers

From the documentation it returns false if no item is available to take i.e. the bag is empty. As it is a thread-safe collection there should be no issues around 'empty' and multiple threads.

You have to take the documentation for result T as well as the return value into consideration:

result T: When this method returns, result contains the object removed from the ConcurrentBag or the default value of T if the bag is empty.

Return: true if an object was removed successfully; otherwise, false.

http://msdn.microsoft.com/en-us/library/dd287255.aspx

like image 197
Tim Lloyd Avatar answered Oct 20 '22 15:10

Tim Lloyd