如何中止/取消 TPL 任务?

编程入门 行业动态 更新时间:2024-10-11 13:23:22
本文介绍了如何中止/取消 TPL 任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在一个线程中,我创建了一些 System.Threading.Task 并启动每个任务.

In a thread, I create some System.Threading.Task and start each task.

当我执行 .Abort() 来终止线程时,任务不会中止.

When I do a .Abort() to kill the thread, the tasks are not aborted.

如何将 .Abort() 传输到我的任务?

How can I transmit the .Abort() to my tasks ?

推荐答案

你不能.任务使用线程池中的后台线程.也不推荐使用 Abort 方法取消线程.你可以看看 以下博客文章解释了使用取消令牌取消任务的正确方法.举个例子:

You can't. Tasks use background threads from the thread pool. Also canceling threads using the Abort method is not recommended. You may take a look at the following blog post which explains a proper way of canceling tasks using cancellation tokens. Here's an example:

class Program { static void Main() { var ts = new CancellationTokenSource(); CancellationToken ct = ts.Token; Task.Factory.StartNew(() => { while (true) { // do some heavy work here Thread.Sleep(100); if (ct.IsCancellationRequested) { // another thread decided to cancel Console.WriteLine("task canceled"); break; } } }, ct); // Simulate waiting 3s for the task to complete Thread.Sleep(3000); // Can't wait anymore => cancel this task ts.Cancel(); Console.ReadLine(); } }

更多推荐

如何中止/取消 TPL 任务?

本文发布于:2023-11-13 04:27:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:TPL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!