Created
September 8, 2021 23:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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