locked
How Parallel.ForEach works internally RRS feed

  • Question

  • i just like to know how Parallel.ForEach() works?

    does it start multiple thread or it is not at all related with thread?

    what is the difference between Parallel.ForEach & Task Parallel library ?

    please explain my 3 points in details with example for better understanding. thanks

    var list = new[] 
    { 
        "http://google.com", 
        "http://yahoo.com", 
        "http://stackoverflow.com" 
    }; 
    
    var tasks = Parallel.ForEach(list,
            s =>
            {
                using (var client = new WebClient())
                {
                    Console.WriteLine("starting to download {0}", s);
                    string result = client.DownloadString((string)s);
                    Console.WriteLine("finished downloading {0}", s);
                }
            });

    Sunday, November 16, 2014 6:17 PM

Answers

  • Hi,

    Parallel.Foreach() works with multiple threads and is a part of the Task Parallel Library (TPL).

    However, the parallel class will decide if multithreading (and especially using multiple cores) makes sense and is appropriate. That is, if you run on a single-core machine, for example, it will default to sequential processing. There is a big difference between using plain TPL (Creating Task objects and starting them) or using the Parallel class:

    The parallel class has algorithms that figure out an optimal batch size. Therefore, if you have, say, 100'000 objects, it will not create a task for every single object and therefore reduce a lot of overhead and be much faster compared to Tasks.

    A very interesting guide can be found here: http://www.albahari.com/threading/part5.aspx

    Another interesting document is this one: http://download.microsoft.com/download/B/C/F/BCFD4868-1354-45E3-B71B-B851CD78733D/WhenToUseParallelForEachOrPLINQ.pdf

    It compares Parallel to "Parallel LINQ (PLINQ)". You can find an example similar to yours in the "Thread local storage" section on page nr. 8.

    Rgds MM


    • Edited by Manuel MeyerMVP Sunday, November 16, 2014 7:37 PM Added section
    • Proposed as answer by Magnus (MM8)MVP Sunday, November 16, 2014 9:06 PM
    • Marked as answer by Barry Wang Tuesday, November 25, 2014 1:49 AM
    Sunday, November 16, 2014 7:33 PM