温馨提示×

C#中parallel.foreach怎么使用

小亿
96
2023-07-12 23:06:50
栏目: 编程语言

在C#中,Parallel.ForEach方法可以用于并行地迭代一个集合。它的使用方法如下:

  1. 首先,确保你的项目中引用了System.Threading.Tasks命名空间,因为Parallel.ForEach方法位于该命名空间中。

  2. 创建一个要迭代的集合,比如List或数组。

  3. 使用Parallel.ForEach方法来并行地迭代集合。方法的基本语法如下:

Parallel.ForEach(collection, (item) =>
{
// 在这里处理每个元素的逻辑
});

其中,collection是要迭代的集合,item是集合中的每个元素。

  1. 在lambda表达式中,编写处理每个元素的逻辑。这个逻辑将在并行执行的线程中执行。

下面是一个完整的示例代码:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Parallel.ForEach(numbers, (number) =>
{
Console.WriteLine(number * 2);
});
Console.ReadLine();
}
}

上述代码创建了一个包含整数的List,并使用Parallel.ForEach方法并行地将每个元素乘以2并输出结果。

0