我该如何中止/取消TPL任务?

编程入门 行业动态 更新时间:2024-10-11 09:29:37
本文介绍了我该如何中止/取消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方法还取消线程不推荐。你可以看看的following博客文章这也解释了取消使用取消标记任务的正确方法。这里有一个例子:

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:28:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583427.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我该   TPL

发布评论

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

>www.elefans.com

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