mike01010
mike01010

Reputation: 6048

does BlockingCollection block when adding items ever? and why if so?

We're using Parallel.foreach to consume items from a blocking collection. I know that by default partioning happens when this is done. I'd like to understand more how this may affect locks/blocking on a BlockingCollection. Is there any cases where an add operation on the blocking collection could be blocked when threads are consuming?

thanks

Upvotes: 3

Views: 3802

Answers (1)

SwDevMan81
SwDevMan81

Reputation: 49978

It could (see How to: Add and Take Items Individually from a BlockingCollection)

This first example shows how to add and take items so that the operations will block if the collection is either temporarily empty (when taking) or at maximum capacity (when adding), or a specified timeout period has elapsed. Note that blocking on maximum capacity is only enabled when the BlockingCollection has been created with a maximum capacity specified in the constructor.

So it will block on adding if the collection is at maximum capacity.

If you consume the items in a foreach loop, adding items will not block during this, but there are a couple of things you will need to note:

  1. There is no guarantee that the items are enumerated in the same order in which they are added by the producer threads.
  2. It is important to understand that this kind of enumeration (foreach) represents a snapshot of the collection at a precise point in time. If other threads are adding or removing items concurrently while you are executing the loop, then the loop might not represent the actual state of the collection.

Upvotes: 3

Related Questions