Home >Backend Development >C++ >How Can I Properly Stop a Task Upon Cancellation in C#?
Effectively Handling Task Cancellation in C#
The CancellationToken.CancelNotification
method alone doesn't stop a running task; it merely signals cancellation. To ensure a task terminates cleanly when cancelled, you must actively incorporate cancellation handling within the task's logic.
Leveraging the Task-Based Asynchronous Pattern (TAP)
The most effective approach involves using TAP and the CancellationToken
consistently:
CancellationToken
: Incorporate a CancellationToken
parameter into every method capable of being cancelled.cancellationToken.ThrowIfCancellationRequested()
. If cancellation is detected, throw an exception to halt execution.Revised Code Example with TAP
This improved example demonstrates proper cancellation handling:
<code class="language-csharp">private async Task TryTask() { using (var source = new CancellationTokenSource()) { source.CancelAfter(TimeSpan.FromSeconds(1)); try { Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token); int result = await task; // Await will re-throw any exceptions. Console.WriteLine($"Task completed successfully: {result}"); } catch (OperationCanceledException) { Console.WriteLine("Task cancelled successfully."); } } } private int slowFunc(int a, int b, CancellationToken cancellationToken) { for (int i = 0; i < 1000000; i++) { cancellationToken.ThrowIfCancellationRequested(); // Check for cancellation // ... your long-running operation ... } return a + b; }</code>
Explanation:
using
statement: Ensures the CancellationTokenSource
is properly disposed, even if exceptions occur.try-catch
block: Handles the OperationCanceledException
thrown by cancellationToken.ThrowIfCancellationRequested()
, providing clean cancellation handling.slowFunc
: The cancellationToken.ThrowIfCancellationRequested()
call is strategically placed within the loop, allowing for frequent cancellation checks. This prevents unnecessary work after cancellation is requested.This revised approach guarantees that the task will stop promptly when cancellation is requested, preventing resource leaks and improving overall application responsiveness.
The above is the detailed content of How Can I Properly Stop a Task Upon Cancellation in C#?. For more information, please follow other related articles on the PHP Chinese website!