This may be a tricky question to ask, but what I have is a DataTable that contains 1000 rows. Foreach of these rows I want to process on a new thread. However I want to limit the threads to 4 threads. So basically I’m constently keeping 4 threads running until the whole datatable has been processed.
currently I have this;
foreach (DataRow dtRow in urlTable.Rows)
{
for (int i = 0; i < 4; i++)
{
Thread thread = new Thread(() => MasterCrawlerClass.MasterCrawlBegin(dtRow));
thread.Start();
}
}
I know this is backwards but i’m not sure how to achieve what I’m looking for. I thought of a very complicated while loop but maybe that’s not the best way? Any help is always appreciated.
Simplest solution would be in case you have 4 CPU cores – Parallel LINQ +Degree of parallelism == 4 would give you one threads per CPU core, otherwise you have manually distribute records between threads/tasks, see both solutions below:
PLINQ solution:
Manual distribution:
You can distribute items by worker threads manually using simple trick:
N-thread would pick up each
N+4item from the input list, for instance:0+4== 0, 3, 7…1+4== 1, 4, 8…2+4== …Task Parallel Library solution:
MSDN: