Skip to content

Instantly share code, notes, and snippets.

@ForNeVeR
Created December 5, 2023 21:39
Show Gist options
  • Save ForNeVeR/b570a0fb84b2e0e934409b9e19ec7f62 to your computer and use it in GitHub Desktop.
Save ForNeVeR/b570a0fb84b2e0e934409b9e19ec7f62 to your computer and use it in GitHub Desktop.
Thread abort in modern .NET.
// 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<Task>? GetScheduledTasks() => null;
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment