CSharp · Console
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
TaskScheduler scheduler = new ConcurrentExclusiveSchedulerPair(
TaskScheduler.Default, maxConcurrencyLevel: 3).ConcurrentScheduler;
TaskFactory taskFactory = new TaskFactory(scheduler);
Stopwatch stopwatch = Stopwatch.StartNew();
Task[] tasks = Enumerable.Range(1, 12).Select(i => taskFactory.StartNew(async () =>
{
Thread.Sleep(500); // This counts towards the maxConcurrencyLevel
Console.WriteLine($"Task: {i}, Elapsed: {stopwatch.Elapsed}");
await Task.Delay(500); // This doesn't count towards the maxConcurrencyLevel
}).Unwrap()).ToArray();
Task.WaitAll(tasks);
}
}