using System.Threading; static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); Task.Run(() => { // Long-running task that can be cancelled while (!cts.Token.IsCancellationRequested) { // Do some work } }, cts.Token); // Cancel the task after 5 seconds Thread.Sleep(5000); cts.Cancel(); }
using System.Threading; static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); try { // Synchronous operation that can be cancelled while (true) { // Do some work cts.Token.ThrowIfCancellationRequested(); } } catch (OperationCanceledException ex) { Console.WriteLine("Operation cancelled."); } }In this example, a synchronous operation is performed within a try-catch block. The CancellationTokenSource is used to check for cancellation using the ThrowIfCancellationRequested method. If cancellation is requested, an OperationCanceledException is thrown and caught, allowing for graceful termination of the operation. Package/library: System.Threading