如何中止/取消TPL任务?在一个线程中,我创建了一些System.Threading.Task开始每一项任务。当我做一个.Abort()若要终止线程,任务不会中止。我如何传送.Abort()我的任务?
3 回答
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
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(); }}
- 3 回答
- 0 关注
- 506 浏览
添加回答
举报
0/150
提交
取消