用Task代替TheadPool
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(); } } }