我想并行运行一部分代码。 目前我正在使用 Parallel.For
如何让10、20或40个线程同时运行
我当前的代码是:
Parallel.For(1, total, (ii) =>
{
doJob(ii);
});
请您参考如下方法:
ParallelOptions opts = new ParallelOptions() { MaxDegreeOfParallelism = 20}
Parallel.For(1, total,opts, (ii) =>
{
doJob(ii);
});
但我鼓励您阅读文档,因为它说明了一些您需要考虑的有趣事实,例如:
By default, For and ForEach will utilize however many threads the underlying scheduler provides, so changing MaxDegreeOfParallelism from the default only limits how many concurrent tasks will be used.
此外,它还提供了一些指导:
The setting exists predominantly to provide control for advanced usage. For example, if you know that a particular algorithm you're using won't scale beyond a certain number of cores, you can set the MaxDegreeOfParallelism property to avoid wasting cycles on additional cores. Or, if you're running multiple algorithms concurrently and want to manually divide up how much of the system they could utilize, you can set a MaxDegreeOfParallelism value for each.
