nooby nooby - 2 months ago 12
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++)

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

and if so, how would I cap the threads ?


What you are looking for is the parallel for


for(int i=0; i <=10; i++) 

Becomes this:

Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 5 }, 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:

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: