Cheetah
Cheetah

Reputation: 14379

IProducerConsumerCollection<T>.TryAdd/.TryTake - when do they return true/false?

When I call IProducerConsumerCollection<T>.TryAdd(<T>) or IProducerConsumerCollection<T>.TryTake(out <T>) will these ever fail because another thread is using the collection?

Or is it the case that if there is space to Add or something to Take even after the other thread has finished with the collection, it will always return true?

Nothing that I can see here: http://msdn.microsoft.com/en-us/library/dd287147.aspx

Upvotes: 3

Views: 664

Answers (2)

Andrey Taptunov
Andrey Taptunov

Reputation: 9495

For example, BlockingCollection<T> which is a high-level abstraction over the interface (it doesn't implement the interface though) with bounding and blocking capabilities may throw one of the following:

  • ObjectDisposedException on TryAdd(T) or TryTake(T) once the collection is disposed.
  • InvalidOperationException on TryAdd(T) if it's marked as complete for addition. Think about situation when you add values to a collection from 2 producers, one marks collection as complete, then another one tries to add to collection.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500805

While in theory the collections could reject take/add requests for any reason, the only reason I know about is Add failing because the collection has reached its capacity, and Take failing because the collection is empty.

The collections are designed from the get-go to be used from multiple threads - so if there are items left, even if two threads try to Take at the same time, they should both get an item and a return value of true.

Upvotes: 6

Related Questions