using System.Collections.Generic;
using System.Threading.Tasks;
public static void Main()
ParallelOptions options = new()
MaxDegreeOfParallelism = 2,
TaskScheduler = new SyncCtxScheduler(SynchronizationContext.Current)
textBox1.AppendText(@$"MaxDegreeOfParallelism: {options
.MaxDegreeOfParallelism}, MaximumConcurrencyLevel: {options
.TaskScheduler.MaximumConcurrencyLevel}" + "\r\n\r\n");
Parallel.ForEach(Enumerable.Range(1, 5), options, x =>
textBox1.AppendText($"Processing #{x}\r\n");
textBox1.AppendText($"Completed #{x}\r\n");
internal sealed class SyncCtxScheduler : TaskScheduler
private readonly SynchronizationContext _ctx;
public SyncCtxScheduler(SynchronizationContext ctx) => _ctx = ctx;
protected override void QueueTask(Task task) => _ctx.Post(s => TryExecuteTask((Task)s), task);
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => SynchronizationContext.Current == _ctx ? TryExecuteTask(task) : false;
protected override IEnumerable<Task> GetScheduledTasks() => null;
private static class textBox1
public static void AppendText(string text) => Console.Write(text);