Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# threading problem

i am trying to simplify problem as follows,

  1. i have around 100+ files that i would like to read and then process the data
  2. For which i maintain array of file names and location
  3. I spawn threads to do the job of reading files.

Now my problem is i would like to make sure that only 5 threads are spawn at a time as starting 100 + threads is not good idea at all.

So please tell me what approach i should use to ensure that the only 5 threads are working at time and as soon as even one of them is done new one can be started.

Thanks all,

like image 491
Anil Namde Avatar asked Mar 02 '10 05:03

Anil Namde


2 Answers

I vote for the task parallel library / Rx (included in .NET 4.0, but downloadable for 3.5):

        var options = new ParallelOptions();
        options.MaxDegreeOfParallelism = 5;

        Parallel.ForEach(GetListOFiles(), options, (file) =>
        {
             DoStuffWithFile(file);
        });

Note that this will use up to 5 threads, but I've seen it use less.

like image 73
ligos Avatar answered Oct 16 '22 21:10

ligos


You should take a look at the

system.threading.threadpool.setmaxthreads

like image 36
rerun Avatar answered Oct 16 '22 21:10

rerun