Home >Backend Development >C++ >How to Properly Abort or Cancel TPL Tasks in C#?

How to Properly Abort or Cancel TPL Tasks in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-25 02:36:09120browse

How to Properly Abort or Cancel TPL Tasks in C#?

Abort/cancel TPL task

In multi-threaded programming, when a thread is terminated using the .Abort() method, tasks created within that thread may continue to run, resulting in unexpected behavior. This article outlines the correct way to abort or cancel a TPL (Task Parallel Library) task.

TPL tasks execute on background threads from the thread pool, they cannot be aborted directly. The recommended approach is to use cancel tags.

Cancellation markers provide a way to signal a task to stop executing. To do this:

  1. Create a CancellationTokenSource.
  2. Get the CancellationToken from the source.
  3. Pass the CancellationToken to the task through the task's constructor or .WithCancellation() method.
  4. When the task needs to be aborted, call Cancel() on the CancellationTokenSource.

The following code example demonstrates this approach:

<code class="language-csharp">class Program
{
    static void Main()
    {
        var cts = new CancellationTokenSource();
        CancellationToken ct = cts.Token;
        Task.Factory.StartNew(() =>
        {
            while (!ct.IsCancellationRequested)
            {
                // 执行一些繁重的工作
                Thread.Sleep(100);
                // 检查取消请求
                if (ct.IsCancellationRequested)
                {
                    Console.WriteLine("任务已取消");
                    break;
                }
            }
        }, ct);

        // 模拟等待任务完成 3 秒
        Thread.Sleep(3000);

        // 无法再等待 => 取消此任务
        cts.Cancel();
        Console.ReadLine();
    }
}</code>

This revised example uses !ct.IsCancellationRequested in the while loop condition for better readability and clarity, directly checking for the cancellation request within the loop. The core functionality remains the same, providing a clean and efficient way to handle task cancellation .

The above is the detailed content of How to Properly Abort or Cancel TPL Tasks 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