Search code examples
c#.netmultithreadingasynchronousblockingcollection

Difference between Take/TryTake and Add/TryAdd on a Blocking Collection


I have been trying to get my head around the Blocking Collection and I came across Take() and TryTake() also Add() and TryAdd()

I understand that if there are no items to take, Take() will wait till an item is added, similarly with Add() if the collection has reached its max limit, it will wait till the item is removed.

As per Josheph Albahari's article on Parallel Programming

"Add and TryAdd may block if the collection size is bounded; Take and TryTake block while the collection is empty."

So Take() and TryTake() both wait for an item to be added. So, if we are not providing any timeout or cancellation token, what is the difference between Take() and TryTake(), shouldn't TryTake() return false straightaway and not wait ? and same for TryAdd() ?


Solution

  • TryTake does not wait, it immediately returns false if collection has nothing. Take will wait for an item.

    TryTake:

    If the collection is empty, this method immediately returns false.

    Take:

    A call to Take may block until an item is available to be removed.