How to start multiple threads using a for loop in C#?
In C#, you can use the Parallel.For method to start a multi-threaded for loop. This method automatically distributes the iterations of the for loop to multiple threads for parallel execution.
Here is an example of using the Parallel.For method to start multiple threads:
using System;
using System.Threading.Tasks;
class Program
{
static void Main()
{
// 定义一个需要循环的数组
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 使用Parallel.For开启多线程的for循环
Parallel.For(0, numbers.Length, i =>
{
// 打印当前线程ID和数组元素的值
Console.WriteLine($"Thread {Task.CurrentId} processed element {numbers[i]}");
});
Console.ReadLine();
}
}
In this example, we are using the Parallel.For method to iterate through the array ‘numbers’. The first parameter of the Parallel.For method represents the starting index of the loop, the second parameter represents the ending index of the loop (not inclusive), and the third parameter is a Lambda expression representing the task of the loop iteration. Within the Lambda expression, we print the current thread ID and the value of the array element.
When we run this program, we can see that the output contains multiple thread IDs and the values of array elements, indicating that multiple threads are executing the loop iterations in parallel.