动作数组未并行执行

时间:2018-08-29 11:50:28

标签: c# parallel-processing

我似乎无法让我的动作并行执行。他们是按顺序执行的。有人可以帮我吗?

Action<Type_arg1,Type_arg2>[] actions = new Action<Type_arg1,Type_arg2>[count];

for (int i = 0; i < count; i++)
    actions[i] = new Action<Type_arg1,Type_arg2>(carryOutAction);
int iter = 0;
Parallel.ForEach(actions, (thisaction) =>
{
    thisaction(arg1,arg2,iter);
    iter++;
});

1 个答案:

答案 0 :(得分:1)

您发布的代码实际上是并行运行的(或者至少是无序的,这很好地暗示了它是并行的)。

PS> scriptcs
scriptcs (ctrl-c to exit or :help for help)

> var count = 20;
>
> Action[] actions = new Action[count];
>
> for (int i = 0; i < count; i++)
* {
*     var contextValue = i;
*     actions[i] = new Action(()=>Console.WriteLine(contextValue));
* }
>
> Parallel.ForEach(actions, (thisaction) =>
* {
*     thisaction();
* });
0
6
7
8
9
11
12
14
16
17
18
19
10
13
3
1
4
2
5
15
{
  "IsCompleted": true,
  "LowestBreakIteration": null
}