Friday, February 11, 2011

C#: Parallel.ForEach Simple Example

The Parallel ForEach feature of .Net 4.0 makes threading even easier.  There is no reason to not try to take advantage of today’s multi-core hardware.  Thread synchronization aside, here’s a very simple sample:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ThreadingSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>();
            for (int i = 0; i < 100; i++)
                numbers.Add(i);

            Parallel.ForEach(numbers, number =>
                {
                    Console.WriteLine(number);
                }
                );

        }
    }
}

7 comments:

  1. Horrible example... Thread contention for the console makes this useless.

    http://msdn.microsoft.com/en-us/library/dd460720.aspx

    ReplyDelete
    Replies
    1. Taught me what I expected.

      Delete
    2. ur such an asshole, why hide ur face, c# god?!

      Delete
  2. The content of the parallel work is not the focus of this example, but the setup is.

    ReplyDelete
  3. may be you should set background-attachment property set to fixed. this will help with not losing focus while reading.

    ReplyDelete
  4. Some more sample

    public void Main()
    {
    dynamic blogs = new List {
    "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 => ProcessBlogs(blog));
    Console.ReadLine();

    }

    private void ProcessBlogs(string blog)
    {
    dynamic client = new WebClient();
    string reply = client.DownloadString(blog);
    Console.WriteLine("Thread: {0} - {1} - Size {2}", Thread.CurrentThread.ManagedThreadId, blog, reply.Length);
    Console.WriteLine(reply);
    }

    ReplyDelete
  5. Some more sample

    public void Main()
    {
    dynamic blogs = new List {
    "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 => ProcessBlogs(blog));
    Console.ReadLine();

    }

    private void ProcessBlogs(string blog)
    {
    dynamic client = new WebClient();
    string reply = client.DownloadString(blog);
    Console.WriteLine("Thread: {0} - {1} - Size {2}", Thread.CurrentThread.ManagedThreadId, blog, reply.Length);
    Console.WriteLine(reply);
    }

    ReplyDelete