Click here to Skip to main content
Click here to Skip to main content

Tagged as

(untagged)

Code Bytes #1 – PLINQ Basics

, 25 Feb 2010
Rate this:
Please Sign up or sign in to vote.
PLINQ /Parallel LINQ is part of the TPL (Task Parallel Library) and it makes your life easier when it comes to multi-core processor programming which is totally different from multithreading which allows more than one thread per process and you have no idea if they will be equally distributed across

PLINQ /Parallel LINQ is part of the TPL (Task Parallel Library) and it makes your life easier when it comes to multi-core processor programming which is totally different from multithreading which allows more than one thread per process and you have no idea if they will be equally distributed across CPU cores. To use PLINQ your objects have to be in memory. This means you can’t use AsParallel on LINQ to SQL until you bring all your query results over to the local machine. When it comes to running your code in parallel the key to remember is that the AsParallel method is you friend. Every result that gets returned after your first call to AsParallel is always a ParallelQuery object. You can get more theory here. Now go code!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace OliverCode.CodeBytes
{
    class ParallelLinqCB
    {
        static void Main(string[] args)
        {
            Action<int> action = (int itemFromList) => Console.Write(itemFromList + ",");
            var lst = Enumerable.Range(1, 10);

            //This will use the maximum number of processors on your machine up to 64
            lst.AsParallel().Select(i => i * i).ForAll(action);
            Console.WriteLine();
            //My machine has 4 cores but i only need it to use up to 2 cores so I use the WithDegreeOfParallelism to restrict it
            lst.AsParallel().WithDegreeOfParallelism(2).ForAll(action);

            Console.Read();
        }
    }
}

Cropped diagram courtesy of MSDN PFX (Parallel Programming Framework)
Code Bytes 1 - PLINQ


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Alphakoda
Software Developer (Senior) 4CoreDev
United States United States
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberognyandim28-Nov-11 5:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140814.1 | Last Updated 25 Feb 2010
Article Copyright 2010 by Alphakoda
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid