Parallel.For vs Parallel.Invoke

时间:2016-06-07 11:24:28

标签: c# multithreading

我有一堆彼此独占的方法,因此可以并行运行。有这样做的好方法吗?到目前为止,我有以下两个实现,但我不确定我是否应该选择其中一个。

使用Parallel.For

Parallel.For(0, 2, i =>
{
    switch (i)
    {
        case 0:
            SomeMethod1();
            break;
        case 1:
            SomeMethod2();
            break;
    }
});

使用Parallel.Invoke

Parallel.Invoke(
    () => { SomeMethod1(); },
    () => { SomeMethod2(); }
);

哪一个最佳表现明智?或者还有另一种方法可以更好地运作吗?

1 个答案:

答案 0 :(得分:4)

I think the performance shouldn't be the issue here. It's all about readable/maintainable code.

  • The first one; I think it's bad practice to put a switch in a Parallel.For. It's confusing and with large switches, it will be unreadable/unmaintainable
  • The second one; Thats better, you might store the actions into a List<Action> first.

Like Henrik already said: Parallel.Invoke(SomeMethod1, SomeMethod2); is (also for me) best readable in this case. (In this case it works, because there aren't parameters/return values)


But as reaction on your question; executing a switch/case each invocation, will generating some extra overhead.