using System; using System.Threading; public class DemoClass { private CancellationTokenSource cts; public void Start() { // create new cancelling token object cts = new CancellationTokenSource(); // Start a new thread Thread t = new Thread(() => { // Continuous loop while (!cts.Token.IsCancellationRequested) { Console.WriteLine("Loop is still executing..."); Thread.Sleep(1000); } }); Console.WriteLine("Press any key to stop the loop."); t.Start(); // Wait for keyboard input, and then cancel Console.ReadKey(); cts.Cancel(); // Release the cancelling token object resources cts.Dispose(); } }
using System; using System.Threading.Tasks; using System.Threading; public class DemoClass { private CancellationTokenSource cts; public async Task StartAsync() { // create new cancelling token object cts = new CancellationTokenSource(); // start a new task with a cancellation token Task t = Task.Run(() => { // continuous loop while (!cts.Token.IsCancellationRequested) { Console.WriteLine("Loop is still executing..."); Thread.Sleep(1000); } }, cts.Token); Console.WriteLine("Press any key to stop the loop."); Console.ReadKey(); // cancel the running task cts.Cancel(); // wait for the task to complete await t; // release the cancelling token object resources cts.Dispose(); } }This example demonstrates the use of CancellationTokenSource in asynchronous task execution. The method starts a new task with a cancellation token and executes a continuous loop until the user cancels the operation. When the user inputs any key, the CancellationTokenSource.Cancel method is called to stop the looping task. Finally, the CancellationTokenSource.Dispose method is called to release the memory resources used by the CancellationTokenSource object. This code uses the .NET Framework package library.