PLinq's AsParallel() makes concurrent calls to underlying IEnumerable

I am trying to play with PLINQ, and I was wondering, if I have an enumerable that, say, reads lines from a file, or stock prices off Yahoo Finance, would AsParallel() call it from one thread or from multiple threads concurrently. Experiment shows that it’s the latter:

class Program
{
    [ThreadStatic]
    static int Index = 0;

    static IEnumerable GetStrings()
    {
        while (true)
        {
            yield return String.Format("Thread {0} String {1}", Thread.CurrentThread.ManagedThreadId, ++Index);
        }
    }

    static void Main(string[] args)
    {
        using (var writer = new ParallelTextWriter("out{0}.txt"))
        {
            GetStrings().AsParallel().Take(1000).ForAll(s => { writer.WriteLine(s); });
        }
    }
}

The output is

Thread 1 String 1
Thread 1 String 2
...
Thread 1 String 800
Thread 3 String 1
Thread 3 String 2
...
Thread 3 String 200

Obviously, the ratio of strings between threads (800/200 or 500/500) could be different each time.

Leave a Reply

Your email address will not be published. Required fields are marked *