Home > Development > Parallel LINQ

Parallel LINQ


This is I guess old news. But you can take a LINQ query and call AsParallel() on it and the engine will take care of this for.

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace ParallelLinqDemo
{

    class Program
    {
        static void Main()
        {

            ConcurrentBag<string> items = new ConcurrentBag<string>();

            Parallel.For(1, 20,
                    x =>
                    {
                        var random = new Random(x).Next(0, 254);
                        char value = (char)random;
                        string temp = new string(value, 10);
                        items.Add(temp);
                    }
                );

            items.AsParallel().OrderBy(x => x).ToList().ForEach(Console.WriteLine);

            Console.ReadKey();
        }
    }
}

Blair..

Advertisements
Categories: Development Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: