Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To terminate a task using C#, you can use the CancellationTokenSource class.

Here's an example:

  1. First, create an instance of the CancellationTokenSource class:
CancellationTokenSource cts = new CancellationTokenSource();
  1. Then, pass the CancellationToken from the CancellationTokenSource to the task you want to cancel.
Task task = Task.Run(() => {
    // your code here
}, cts.Token);
  1. To cancel the task, call the Cancel method on the CancellationTokenSource:
cts.Cancel();
  1. Finally, add a try-catch block to handle the OperationCanceledException that will be thrown when the task is cancelled:
try {
    task.Wait();
}
catch (AggregateException ae) {
    if (ae.InnerExceptions.Any(e => e is OperationCanceledException)) {
        // task was cancelled
    }
    else {
        // handle other exceptions
    }
}