I'm trying to implement a multithread in c#.
The basic idea is:
There will be a lot of thread process calling a function and every thread doesn't end in order they are called.
I want to limit maximum number of thread running.
When a thread is finished, I want to call another thread until everything is done.
So to implement this, I use a list of thread. For every second, I check if there the list is already full and if there's any thread finished its job.
Here is my code:
List<Thread> threadCompany = new List<Thread>();
List<Thread> fireThisGuy = new List<Thread>();
while (i < _finish) {
if (threadCompany.Count < _MAX_THREAD) {
Thread worker = new Thread(delegate() {
CallFunction(i);
});
threadCompany.Add(worker);
i++;
worker.Start();
}
Thread.Sleep(1000); //Wait for a while instead of keep calling if
foreach (Thread worker in threadCompany) {
if (!worker.IsAlive) {
fireThisGuy.Add(worker); //because threadCompany may not be
//modified in iteration.
}
}
foreach (Thread worker in fireThisGuy) {
threadCompany.Remove(worker);
}
fireThisGuy.Clear();
}
This works, but I don't think I'm being elegant and efficient here, how can I improve my code?