






















TheadPool的问题
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var p = new Program(); p.Task(); Console.ReadKey(); p.Signal(); Console.ReadKey(); } CancellationTokenSource cts = new CancellationTokenSource(); void Task() { var random = new Random(); for (int i = 0; i < 100; i++) { var worker = new Task(() => { while (true) { if (random.Next(100) % 2 == 1) { if (cts.IsCancellationRequested) { break; } } else { cts.Token.ThrowIfCancellationRequested(); //异常取消 } Thread.Sleep(100); } }); worker.Start(); worker.ContinueWith(task => { Console.WriteLine("IsCancele={0},IsCompleted={1},IsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted); }); } } void Signal() { cts.Cancel(); } } }
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。