[英]Parallel.for loop Execution
Scenario设想
I need to create n
threads ( not equal to number of function to executes) that execute multiple functions parallel.我需要创建
n
线程(不等于要执行的函数数)来并行执行多个函数。 So my code is所以我的代码是
static void Main()
{
Parallel.For(0, 2, i => // it creates 2 threads as number of iterations.why?
{
method1();
method2();
method3();
method4();
method5();
method6();
method7();
method8();
method9();
method10();
});
}
How to use MaxDegreeOfParallelism
property here in best way?如何以最佳方式在此处使用
MaxDegreeOfParallelism
属性? Can someone please help?有人可以帮忙吗?
It seems that you are looking for Parallel.Invoke instead of Parallel.For
(I can't see any loop in your code):看来您正在寻找Parallel.Invoke而不是
Parallel.For
(我在您的代码中看不到任何循环):
ParallelOptions options = new ParallelOptions() {
//TODO: carry out experiment on your workstation to find out the right number
MaxDegreeOfParallelism = 4,
};
// Run method1..method10 in parallel while using options
Parallel.Invoke(options,
method1,
method2,
method3,
method4,
method5,
method6,
method7,
method8,
method9,
method10
);
As you wish如你所愿
var methods = new Action[] {
method1, method2, method3, method4, method5, method6, method7, method8, method9, method10 };
Parallel.For(0, methods.Length, i =>
{
methods[i]();
});
This way you can set the degree of parallelization这样你就可以设置并行度
var options = new ParallelOptions { MaxDegreeOfParallelism = 4 };
Parallel.For(0, methods.Length, options, i =>
When you wrote Parallel.For(0, 2
, it creates a loop for the specified number of elements: from 0 (inclusive) to 2 (exclusive). Therefore, there can be a maximum of two threads.当您编写
Parallel.For(0, 2
,它会为指定数量的元素创建一个循环:从 0(包含)到 2(不包含)。因此,最多可以有两个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.