gpt4 book ai didi

C#并行,如何设置线程数

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:44 34 4
gpt4 key购买 nike

我想并行运行一部分代码。目前我正在使用 Parallel.For

如何让10、20或40个线程同时运行

我当前的代码是:

        Parallel.For(1, total, (ii) =>
{
doJob(ii);
});

最佳答案

设置MaxDegreeOfParallelism选项:

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.

关于C#并行,如何设置线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943721/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com