gpt4 book ai didi

c# - 并行 Linq : Ordered treatment

转载 作者:行者123 更新时间:2023-11-30 16:19:27 24 4
gpt4 key购买 nike

我正在学习 70-516 MS 考试的资料,我看到了他们解释说如果我们使用 AsOrdered 方法,我们可以确保在进行并行处理的同时进行有序处理的部分。

但是,运行下面的示例不会按顺序输出结果。

基本上,下面的示例代码从 10 个整数的可枚举集合开始,然后对其进行并行化、排序,最后仅选择 Compute 函数返回偶数的元素进行过滤。 Compute 函数在 1 秒延迟后仅返回输入

private void TestLinqParallel()
{
Stopwatch sw = new Stopwatch();
sw.Start();
var source = Enumerable.Range(1, 10).AsParallel().AsOrdered();
var evenNums = from num in source
where Compute(num) % 2 == 0
select num;
evenNums.ForAll(ev =>
{
Debug.WriteLine(string.Format("{0} on Thread {1}", ev, Thread.CurrentThread.GetHashCode()));

});
sw.Stop();
Debug.WriteLine(string.Format("Done {0}", sw.Elapsed));
}
public int Compute(int num)
{
Debug.WriteLine(string.Format("Computing {0} on Thread {1}", num, Thread.CurrentThread.GetHashCode()));
Thread.Sleep(1000);
return num;
}

书上说

The results are ordered, at least for the even numbers, which is what the AsOrdered extension method is guaranteeing.

但这是我的结果.. 4 的处理先于 2 的处理

Computing 4 on Thread 11
Computing 3 on Thread 10
Computing 2 on Thread 12
Computing 1 on Thread 6
4 on Thread 11
Computing 7 on Thread 11
Computing 6 on Thread 6
2 on Thread 12
Computing 8 on Thread 12
Computing 5 on Thread 10
Computing 9 on Thread 11
6 on Thread 6
Computing 10 on Thread 6
8 on Thread 12
10 on Thread 6
Done 00:00:03.0561023

有人能帮忙吗?

最佳答案

ForAll 是并行化的。这意味着所有排序保证都超出了窗口,因为您的代码主体是并发执行的。尝试 foreach 循环。

关于c# - 并行 Linq : Ordered treatment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316955/

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