Ask Your Question
2

What is the process for terminating a task using C#?

asked 2021-09-07 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-07-06 14:00:00 +0000

devzero gravatar image

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
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-07 11:00:00 +0000

Seen: 14 times

Last updated: Jul 06 '22