Reputation: 6081
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?
Upvotes: 12
Views: 3305
Reputation: 239704
Given that you're dealing with multithreading, there's nothing to stop another thread from adding an item to the bag between the moment at which TryTake
has decide to return false (and set it's return value to default(T)
), and the moment at which the call to TryTake
actually returns to your code.
So by the time you're able to handle the false result, there may actually be an item in the bag.
Upvotes: 3
Reputation: 38444
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
Upvotes: 3