using System.Threading.Tasks;
public static void Main()
var cts = new CancellationTokenSource();
Console.WriteLine("Before starting task");
var task = Task.Run(() => DoSomething(cts.Token), cts.Token);
Console.WriteLine("Before cancelling task");
Console.WriteLine("Exception caught", ex);
private static async Task DoSomething(CancellationToken ct)
while (!ct.IsCancellationRequested)
Console.WriteLine("Hello World");
if(ct.IsCancellationRequested) Console.WriteLine("erik is cool.");