Book Image

Learning .NET High-performance Programming

By : Antonio Esposito
Book Image

Learning .NET High-performance Programming

By: Antonio Esposito

Overview of this book

Table of Contents (16 chapters)
Learning .NET High-performance Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Data parallelism with PLINQ


PLINQ is the framework required to use LINQ within the TPL parallel framework. In .NET, it is straightforward to use parallelism against any LINQ query because we simply need to add the AsParallel method at the root of the query to switch the execution from the simple LINQ engine to PLINQ with TPL support.

The following example will execute two different where conditions against an enumerable using PLINQ:

static void Main(string[] args)
{
    //a dataset
    var items = Enumerable.Range(1, 100);

    //multi-level in-memory where executed as data parallelism
    var processedInParallel = items.AsParallel()
        .Where(x => CheckIfAllowed1(x))
        .Where(x => CheckIfAllowed2(x))
        .ToArray();

    Console.ReadLine();
}

private static bool CheckIfAllowed2(int x)
{
    Console.WriteLine("Step 2 -> Checking {0}", x);
    //some running time
    Thread.Sleep(1000);
    return x % 3 == 0;
}

private static bool CheckIfAllowed1(int x)
{
    Console...