nooby nooby - 1 month ago 8
C# Question

c# how to thread through loops

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 ?

Answer

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

Comments