3

I'm following the material from the 70-516 MS exam, and I came across the section where they explain that we can ensure an ordered treatment while doing parallel processing if we use the AsOrdered method.

However, running the example below does not ouput the results in order.

Basically, the sample code below starts with an enumerable collection of 10 integers, which is then parallelised, then ordered and finally filtered by only selecting element for which the Compute function returns a even number. The Compute function just returns the input, after a 1 sec delay

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 book states

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

But here are my results.. The processing of 4 comes before the processing of 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

Can anyone help?

4

1 回答 1

3

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

于 2013-03-09T23:13:43.583 回答