using System.Threading; using System.Threading.Tasks; public async Task DoAsyncOperation(CancellationToken cancellationToken) { // An example of an async operation that can be cancelled await Task.Delay(5000, cancellationToken); } // Create a CancellationTokenSource and pass its CancellationToken to the async operation var cts = new CancellationTokenSource(); var token = cts.Token; var task = DoAsyncOperation(token); // Cancel the operation after a 2 second delay await Task.Delay(2000); cts.Cancel(); // Wait for the operation to complete or cancel try { await task; } catch (OperationCanceledException) { // Gracefully handle the cancellation }
using System.Threading; using System.Threading.Tasks; public void DoLongRunningOperation(CancellationToken cancellationToken) { // An example of a long-running operation that can be cancelled for (int i = 0; i < 100000; i++) { if (cancellationToken.IsCancellationRequested) { // Gracefully handle the cancellation break; } // Perform some operation that takes a long time } } // Create a CancellationTokenSource and pass its CancellationToken to the long-running operation var cts = new CancellationTokenSource(); var token = cts.Token; var task = Task.Run(() => DoLongRunningOperation(token)); // Cancel the operation after a 2 second delay await Task.Delay(2000); cts.Cancel(); // Wait for the operation to complete or cancel try { await task; } catch (OperationCanceledException) { // Gracefully handle the cancellation }In this example, we create a CancellationTokenSource and pass its CancellationToken to a long-running operation. We then cancel the operation after a 2 second delay, and wait for the operation to complete or cancel. This example does not use any external package library.