Ok here my question. I want to start threads until a certain number. Lets say 100. So it will start starting threads and check continuously number of running threads. When the maximum number reached it will stop starting new threads. But with a proper checking interval or completed thread will signal and it will start new thread.
With this way, i will always have certain number of running threads.
I managed this with using sleep and permanent while. So i keep checking total running thread count with a given interval and if thread is completed, dispose it and start a new one.
But my solution is not coming me as a proper way. I suppose it would be better if the completed thread would signal and then checker would start a new one if we are below of the maximum number of threads threshold.
I saw many threadpool examples but most of them not contains any queued pooling with maximum amount of running threads. What i mean is, they just keep starting threads until they are done. But lets say i have 500k urls to harvest. I can not just start all of them in a for loop with thread pool.
platform is c# 4.5 WPF application
And here below is my solution. Actually i am looking for a better one. Not improving this one.
private void Button_Click_4(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
startCrawler();
});
}
void startCrawler()
{
int irMaximumThreadcount = 100;
List<Task> lstStartedThreads = new List<Task>();
while (true)
{
for (int i = 0; i < lstStartedThreads.Count; i++)
{
if (lstStartedThreads[i].IsCompleted == true)
{
lstStartedThreads[i].Dispose();
lstStartedThreads.RemoveAt(i);
}
}
if (lstStartedThreads.Count < irMaximumThreadcount)
{
var vrTask = Task.Factory.StartNew(() =>
{
func_myTask();
});
lstStartedThreads.Add(vrTask);
}
System.Threading.Thread.Sleep(50);
}
}
void func_myTask()
{
}