How can I count active threads in an array and avoid “collection was modified” errors?
-
26-04-2021 - |
Question
I have a collection of Threads in C# (List<Thread>
) which at certain intervals I want to get the number of them which are actively doing work.
Currently I set the individual threads to null when they are completed. Therefore:
private int AliveThreads()
{
lock (ThreadCollection)
{
return ThreadCollection.Count(t => t != null);
}
}
I am attempting to use lock
to avoid having the error "Collection was modified" but this isn't working. I still get this error from time to time.
Is there something else that might be better?
Solution
I would just use an interlocked counter; increase this (Interlocked.Increment) before starting each thread, and have each thread call Interlocked.Decrement just before they exit. Then you can use Thread.VolatileRead at any point to see how many are active, without any collection.
However, specifically to address the question: if you are using a collection the threads setting the item to null should lock, too:
lock(ThreadCollection)
{
ThreadCollection[index] = null;
}
The counter seems far cleaner to me.
OTHER TIPS
Your code:
lock (ThreadCollection)
{
return ThreadCollection.Count(t => t != null);
}
is only effective when all other operations on ThreadCollection
are also surrounded by a lock()
statement.
to avoid having the error "Collection was modified"
indicates you are not doing that, the error comes from another piece of code.