Home >Backend Development >C++ >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:
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!