Archive

Posts Tagged ‘Concurrency’

Parallel LINQ

March 7, 2010 Leave a comment

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: , , , ,