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?
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.
TryTake(out T) - This method is used to retrieve an element from ConcurrentBag<T>. Note that this method removes the item from the collection.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With