更新 - 更改了问题的标题以反映我真正追求的内容
考虑以下代码:
// this query generates 12 instances of Func<int>, which each when executed
// print something to the console and wait for 1 second.
var actions = Enumerable.Range(0, 12).Select(i => new Func<int>(() =>
{
Console.WriteLine("{0} - waiting 1 sec", i);
Thread.Sleep(1000);
return 1;
}));
// define a parallel query. Note the WithDegreeOfParallelism call here.
var query = from action in actions.AsParallel().WithDegreeOfParallelism(12)
select action();
// execute, measuring total duration
var stopw = Stopwatch.StartNew();
query.ToList();
Console.WriteLine(stopw.Elapsed);
Console.WriteLine(Environment.ProcessorCount); // 3 on my machine
当省略对 的调用时WithDegreeOfParallelism
,它分 4 个块执行,总共需要大约 4 秒,这是我所期望的,因为我的 CPU 计数是 3。
但是,当用任何大于 4 的数字调用WithDegreeOfParallelism
时,我总是得到 3 个块,并且总持续时间不低于 3 秒。我预计 12 的值将获得(略多于)1 秒的总持续时间。
我错过了什么?以及如何强制并行执行超过 4 个非 CPU 密集型任务,这就是我所追求的?
更新:我当然可以回去手动启动线程,但我希望新的 PFX 库能让这更容易一些......无论如何,下面的代码给了我大约 1 秒的总执行时间
List<Thread> threads = new List<Thread>();
for (int i = 0; i < 12; i++)
{
int i1 = i;
threads.Add(new Thread(() =>
{
Console.WriteLine(i1);
Thread.Sleep(1000);
}));
}
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());