对于下面的测试程序来说,它似乎并没有做深蹲。这是因为我正在用一个小列表进行测试吗?
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 秒。
任务并行库关心的是静态类型的序列。它应该是IParallelEnumerable<T>
由 TPL 处理的操作。您正在将集合投射回IEnumerable<T>
你打电话时Test
。因此,编译器会解析.Where
调用序列System.Linq.Enumerable.Where
扩展方法而不是 TPL 提供的并行版本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)