// See https://aka.ms/new-console-template for more information using System.Collections; using System.Runtime; internal class Program { public static void Main(string[] args) { var task = StartWork(); Thread.Sleep(1000); MyTaskScheduler.GlobalCancellation.Cancel(); Thread.Sleep(500); } public static Task StartWork() { return MyTask.Run(() => { Console.WriteLine("Ticking…"); try { while (true) { } } finally { Console.WriteLine("Finished?!"); } }); } } internal static class MyTask { public static Task Run(Action a) => Task.Factory.StartNew( _ => a(), state: null, cancellationToken: default, TaskCreationOptions.None, MyTaskScheduler.Instance); } internal class MyTaskScheduler : TaskScheduler { internal static readonly MyTaskScheduler Instance = new(); internal static readonly CancellationTokenSource GlobalCancellation = new(); protected override void QueueTask(Task task) { Task.Run(() => { ControlledExecution.Run(() => { TryExecuteTask(task); }, GlobalCancellation.Token); }); } protected override IEnumerable? GetScheduledTasks() => null; protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => false; }