To cancel a task in C#, you can make use of a Cancellation Token. A cancellation token is an object that is passed to a task and is monitored by the task. If the token is cancelled, the task is notified and can gracefully terminate.
Here's an example of how to cancel a task in C#:
main.cs971 chars38 lines
In this example, we first create a CancellationTokenSource object and a CancellationToken object from it. Then we create a Task object with Task.Run() and pass in a lambda expression that contains our long-running code. Inside this lambda expression, we check for cancellation using the cancellationToken.IsCancellationRequested property. If the token is cancelled, we print a message to the console and throw an OperationCanceledException.
We then delay cancellation using the Task.Delay() method and then call the cancellationTokenSource.Cancel() method to cancel the task. Finally, we use a try-catch block to catch the OperationCanceledException that is thrown when the task is cancelled.
By using a CancellationToken in your tasks, you can gracefully cancel long-running tasks and prevent them from running indefinitely.
gistlibby LogSnag