Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Threadpool - limit number of threads

I am developing a console app.

I want to use a Threadpool to perform web downloads. Here is some fake code.

 for (int loop=0; loop< 100; loop++)  {      ThreadPool.QueueUserWorkItem(new WaitCallback(GetPage), pageList[loop]);  }   snip  private static void GetPage(object o) {     //get the page } 

How do I prevent my code from starting more than two (or ten, or whatever) simultaneous threads?

I have tried

    ThreadPool.SetMaxThreads(1, 0);     ThreadPool.SetMinThreads(1, 0); 

But they seem to have no impact.

like image 624
Bryan Avatar asked Apr 26 '12 22:04

Bryan


1 Answers

I would use Parallel.For and set MaxDegreeOfParallelism accordingly.

Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 10 },   i =>   {     GetPage(pageList[i]);   }); 
like image 51
Brian Gideon Avatar answered Oct 06 '22 00:10

Brian Gideon