Home >Backend Development >C++ >How Can I Properly Stop a Task Upon Cancellation in C#?

How Can I Properly Stop a Task Upon Cancellation in C#?

DDD
DDDOriginal
2025-01-26 12:36:10679browse

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:

  • Pass CancellationToken: Incorporate a CancellationToken parameter into every method capable of being cancelled.
  • Regular Cancellation Checks: Within these methods, periodically check the token's status using 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn