Skip to content

Instantly share code, notes, and snippets.

@fabio-stein
Created September 8, 2021 23:50
Show Gist options
  • Save fabio-stein/81919e443449aa69e5cbe1f434a17d6c to your computer and use it in GitHub Desktop.
Save fabio-stein/81919e443449aa69e5cbe1f434a17d6c to your computer and use it in GitHub Desktop.
Example - Run Tasks in parallel with PLINQ controlling/limiting max number of threads
using System;
using System.Linq;
using System.Threading.Tasks;
class Program
{
const int generatedTasks = 10;
const int maxThreads = 2;
static Random random = new Random();
static void Main(string[] args)
{
var tasks = Enumerable.Range(0, generatedTasks).Select(id => Task.Run(async () => await HeavyTask(id)));
var results = tasks
.AsParallel()
.AsOrdered() //Optional
.WithDegreeOfParallelism(maxThreads)
.Select(t => t.Result)
.ToList();
}
static async Task<int> HeavyTask(int id)
{
Console.WriteLine("Starting Task #" + id);
await Task.Delay(random.Next(3000, 10000));
Console.WriteLine("Finished Task #" + id);
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment