究竟如何进行AsParallel工作?工作、AsParallel

2023-09-03 02:47:40 作者:几许痴情,几许伤痛

这似乎并没有做下蹲以下测试程序。难道是因为我测试用小单子?

It doesn't seem to do squat for the following test program. Is this because I'm testing with a small list?

static void Main(string[] args)
{
    List<int> list = 0.UpTo(4);

    Test(list.AsParallel());
    Test(list);
}

private static void Test(IEnumerable<int> input)
{
    var timer = new Stopwatch();
    timer.Start();
    var size = input.Count();
    if (input.Where(IsOdd).Count() != size / 2)
        throw new Exception("Failed to count the odds");

    timer.Stop();
    Console.WriteLine("Tested " + size + " numbers in " + timer.Elapsed.TotalSeconds + " seconds");
}

private static bool IsOdd(int n)
{
    Thread.Sleep(1000);
    return n%2 == 1;
}

两个版本都需要4秒运行。

Both versions take 4 seconds to run.

推荐答案

任务并行库关心的的静态类型的序列。它应该是 IParallelEnumerable&LT; T&GT; 的操作由TPL处理。您是铸造收集回的IEnumerable&LT; T&GT; 当你调用测试。因此,编译器将解决在序列。凡呼叫 System.Linq.Enumerable.Where 扩展方法,而不是由TPL提供的并行版本。

Task Parallel Library cares about the static type of the sequence. It should be IParallelEnumerable<T> for the operations to be handled by the TPL. You are casting the collection back to IEnumerable<T> when you call Test. Therefore, the compiler will resolve .Where call on the sequence to System.Linq.Enumerable.Where extension method instead of the parallel version provided by the TPL.