Parallel.Invoke 和 Parallel.ForEach(当用于执行操作时)功能相同,但确实有人特别希望集合是一个数组。考虑以下示例:
List<Action> actionsList = new List<Action>
{
() => Console.WriteLine("0"),
() => Console.WriteLine("1"),
() => Console.WriteLine("2"),
() => Console.WriteLine("3"),
() => Console.WriteLine("4"),
() => Console.WriteLine("5"),
() => Console.WriteLine("6"),
() => Console.WriteLine("7"),
() => Console.WriteLine("8"),
() => Console.WriteLine("9"),
};
Parallel.ForEach<Action>(actionsList, ( o => o() ));
Console.WriteLine();
Action[] actionsArray = new Action[]
{
() => Console.WriteLine("0"),
() => Console.WriteLine("1"),
() => Console.WriteLine("2"),
() => Console.WriteLine("3"),
() => Console.WriteLine("4"),
() => Console.WriteLine("5"),
() => Console.WriteLine("6"),
() => Console.WriteLine("7"),
() => Console.WriteLine("8"),
() => Console.WriteLine("9"),
};
Parallel.Invoke(actionsArray);
Console.ReadKey();
此代码在一次运行时产生此输出。它的输出通常每次都以不同的顺序排列。
0 5 1 6 2 7 3 8 4 9
0 1 2 4 5 6 7 8 9 3