1

Hello I was wondering how people make loops threaded for example

for(int i = 0; i<10; i++)
{
     Console.WriteLine(i);
}

Is it possible to have one thread for every loop? so, Thread 1: 0 Thread 2: 1 Thread 3: 2 ect..

and if so, how would I cap the threads ?

1 Answers1

4

What you are looking for is the parallel for

This:

for(int i=0; i <=10; i++) 
{  
    Console.WriteLine(i); 
}

Becomes this:

Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 5 }, i =>
{
    Console.WriteLine(i);
});

This will spawn one task per iteration of the loop. One of the overloads of parallel takes in the parallel options which lets set the maximum number of tasks running cuncurrently. Official docs: https://msdn.microsoft.com/en-us/library/dd992418(v=vs.110).aspx

Note there is some difference between a thread and a task in C#: What is the difference between task and thread?

If you have a list of items to process I recommend the parallel foreach: https://msdn.microsoft.com/en-us/library/dd460720(v=vs.110).aspx

Community
  • 1
  • 1
Wallace
  • 5,319
  • 4
  • 17
  • 9