# Collection to hold maximum number of running Tasks

I need a collection/bag (something) that will hold some maximum number of running Task objects. Adding a new running Task to the collection should block the calling thread (there are many threads trying to add a task so it should be thread safe) until there is an available slot for the new Task to be added if the maximum number of running tasks is reached. This is what I have so far and it is working fine.

Can you find any problems with this code? Or is there some built-in class that can handle this kind of task?

public class ConcurrentTaskLimiter
{
public int MaxWorkingTasks { get; }

{
if ((1 <= maxWorkingTasks) == false)

for (int i = 0; i < MaxWorkingTasks; i++)
{
_finished[i] = true;
}
}

{
if (t == null)
throw new ArgumentNullException(nameof(t));

return;

lock (this)
{
int i;
while (true)
{
for (i = 0; i < MaxWorkingTasks; i++)
{
if (_finished[i])
{
_finished[i] = false;
return;
}
}
_finished[i] = true;
}
}
}
}


What you have described here is a Producer- Consumer relationship. .Net has a BlockingCollection that performs exactly what you are trying to create here

public BlockingCollection(
IProducerConsumerCollection<T> collection,
int boundedCapacity
)


You could use a ConcurrentBag as the underlying store or any ConcurrentCollection of your choice and the boundedCapacitycan be the maximum number of Tasks that can be added to the collection. An example usage is

BlockingCollection<int> messages = new BlockingCollection<int>(new ConcurrentBag<int>(), 10);

• I thought of BlockingCollection<T> but in this case how am I going to remove the finished tasks efficiently. On every Add I have to .ToArray() on the blocking collection WaitAny(arrayTask), and then instantiate a new BlockingCollection<T> with the finished task removed, and add the new one added. This seems as a lot of unnecessary operations just for the sake of using the BlockingCollection. Or am I missing some obvious solution? – Mihail Shishkov Dec 26 '16 at 9:34
• @MihailShiahkov I will post an example of how to use the same blocking collection as a producer and a consumer shortly – Siobhan Dec 26 '16 at 17:07
• The quotes are misleading. It looks like the OP has said that. I suggest not using it for your own words. – t3chb0t Dec 29 '16 at 14:25
• Will update my review @t3chb0t – Siobhan Dec 29 '16 at 14:29
• I didn't mean removing everything :-o just the quote formattings where applicable :-) – t3chb0t Dec 29 '16 at 14:49