CancellationTokenSource cts = new CancellationTokenSource(); Task.Run(() => { while (!cts.Token.IsCancellationRequested) { // do some work } }, cts.Token); // cancel the task after 5 seconds cts.CancelAfter(TimeSpan.FromSeconds(5));
CancellationTokenSource cts = new CancellationTokenSource(); Task.Run(() => { while (!cts.Token.IsCancellationRequested) { // do some work } // clean up resources and throw if cancelled cts.Token.ThrowIfCancellationRequested(); }, cts.Token); // cancel the task after 5 seconds cts.CancelAfter(TimeSpan.FromSeconds(5));This code is similar to the first example, but the task now includes clean up code which will execute if cancellation is requested. It also throws an OperationCanceledException if cancellation is requested to alert the caller. The System.Threading namespace is part of the .NET Standard library.