我有一堆彼此独占的方法,因此可以并行运行。有这样做的好方法吗?到目前为止,我有以下两个实现,但我不确定我是否应该选择其中一个。
使用Parallel.For:
Parallel.For(0, 2, i =>
{
switch (i)
{
case 0:
SomeMethod1();
break;
case 1:
SomeMethod2();
break;
}
});
Parallel.Invoke(
() => { SomeMethod1(); },
() => { SomeMethod2(); }
);
哪一个最佳表现明智?或者还有另一种方法可以更好地运作吗?
答案 0 :(得分:4)
I think the performance shouldn't be the issue here. It's all about readable/maintainable code.
Parallel.For
. It's confusing and with large switches, it will be unreadable/unmaintainableList<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.