标签:style blog io color os ar for sp div
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(); } } }
标签:style blog io color os ar for sp div
原文地址:http://www.cnblogs.com/goodspeed/p/4068794.html