Simple Parallel ForEach threading example

A very efficient and clean way of multi threaded iterating through some lengthy tasks, is by using Parallel.ForEach. It takes a lambda expression with the body to execute for each task in the provided list. In this case we download a couple of weblog homepages to a string and show the length of the downloaded result and the current thread id of the task.

using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelTask
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var blogs = new List<string>
                            {
                                "http://remondo.net",
                                "http://www.nikhilk.net",
                                "http://blogs.teamb.com/craigstuntz",
                                "http://mehmetcatkin.com/",
                                "http://blogs.msdn.com/b/lukeh",
                            };

            Parallel.ForEach(
                blogs, blog =>
                           {
                               var client = new WebClient();
                               string reply = client.DownloadString(blog);

                               Console.WriteLine(
                                   "Thread: {0} - {1} - Size {2}",
                                   Thread.CurrentThread.ManagedThreadId,
                                   blog,
                                   reply.Length);
                           });

            Console.ReadLine();
        }
    }
}

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>