Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a List<BlockingCollection<T>> Thread safe?

I wan't to maintain a list of several BlockingCollections

List<BlockingCollection<ExtDocument>> a = new List<BlockingCollection<ExtDocument>>();

And the check in subthreads if any of the 'queues' still have items pending:

if (a.Where(x => x.IsAddingCompleted).Count > 0)

Is the usage of a List<T> in this case thread-safe if the number of items in the list don't change after the initialisation (the content of the blockinglists inside the collection will change offcourse...)?

Or should i opt for an array of BlockingCollection or the following construction:

BlockingCollection<BlockingCollection<workitem>> a = new BlockingCollection<BlockingCollection<workitem>>();
like image 735
User999999 Avatar asked Sep 26 '14 11:09

User999999


1 Answers

A nice benefit from using an array instead of List<T> is that you can then use BlockingCollection<T>.TakeFromAny and similar methods. Most likely, you're approaching your problem from the wrong angle - your processing threads could then simply do BlockingCollection<T>.TryTakeFromAny, and if it's false, you're done. Completely thread-safe, and rather well performing. So your processing loop will look something like this:

while (BlockingCollection<ExtDocument>.TryTakeFromAny(collections, out workItem) >= 0)
{
  // Do work on workItem
}

// We're done!
like image 135
Luaan Avatar answered Sep 27 '22 20:09

Luaan