using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskCancellationTest
{
class Program
{
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
Handle(cts.Token);
Console.WriteLine("Press <Enter> to cancel tasks.");
Console.ReadLine();
cts.Cancel();
// Won't stop
Console.ReadLine();
}
public static async void Handle(CancellationToken ct)
{
for (int i = 0; i < 10; i++)
{
try
{
ct.ThrowIfCancellationRequested();
await Task.Delay(1000);
Console.WriteLine($"Taks {i} has completed.");
}
catch (Exception ex) when (ex is OperationCanceledException)
{
Console.WriteLine("Task was cancelled.");
return;
}
}
}
}
}