Luna Tech

Tutorials For Dummies.

Parallel LINQ (PLINQ)

2022-02-20


0. What is PLINQ?


1. Example

void Main()
{
	var stopwatch = new Stopwatch();
	stopwatch.Start();

	var result = Enumerable.Range(0,100)
					.AsParallel() // use PLINQ
					.Select(Compute)
					.Sum();
					
	Console.WriteLine(result);
	
	"------------------------".Dump();

	var result2 = Enumerable.Range(0, 100)
				.AsParallel() // use PLINQ
				.Select(Compute)
				.Take(10);

	foreach (var r in result2)
	{
		Console.WriteLine(r); // not ordered
	}
	
	"------------------------".Dump();

	var result3 = Enumerable.Range(0, 100)
			.AsParallel() // use PLINQ
			.AsOrdered() // ordered (will add overhead)
			.Select(Compute)
			.Take(10);

	foreach (var r in result3)
	{
		Console.WriteLine(r); // ordered
	}

    "------------------------".Dump();

    result3.ForAll(Console.WriteLine); // parallel

	Console.WriteLine($"It took: {stopwatch.ElapsedMilliseconds}ms to run");
}

static Random random = new Random();
static int Compute(int value)
{
	var randomMilliseconds = random.Next(10, 50);
	var end = DateTime.Now + TimeSpan.FromMilliseconds(randomMilliseconds);

	while (DateTime.Now < end) { }

	return value + 100;
}