AsParallel究竟是如何工作的?

rip*_*234 7 .net c# plinq

以下测试程序似乎没有下蹲.这是因为我正在测试一个小清单吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

两个版本都需要4秒才能运行.

Meh*_*ari 24

Task Parallel Library关注序列的静态类型.它应该是IParallelEnumerable<T>由TPL处理的操作.您IEnumerable<T>在致电时将集合转回Test.因此,编译器将解析.Where对序列到System.Linq.Enumerable.Where扩展方法的调用,而不是TPL提供的并行版本.


Alf*_*dBr 5

(更新.NET4,因为这个问题在Google搜索AsParallel()时排名很高)

只需进行一些更改,您的示例就可以像我想象的那样工作.

更改List<int> list = 0.UpTo(4);到var list = Enumerable.Range(0, 4);

如果您添加了一个函数重载,并且签名带有ParallelQuery,那么您的示例将会起作用...

    private static void Test(ParallelQuery<int> input)
    {
        var timer = new Stopwatch();
        timer.Start();

        int 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");
    }
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用LINQ语法....

    private static void Test(ParallelQuery<int> list)
    {
        var timer = Stopwatch.StartNew();

        if ((from n in list.AsParallel()
             where IsOdd(n)
             select n).Count() != (list.Count() / 2))
        {
            throw new Exception("Failed to count the odds");
        }

        Console.WriteLine("Tested " + list.Count() + " numbers in " + timer.Elapsed.TotalSeconds + " seconds");
    }
Run Code Online (Sandbox Code Playgroud)

希望这有助于某人!