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?
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:
The counter seems far cleaner to me.