用Task代替TheadPool

TheadPool的问题

  1. 不支持线程的取消、完成、失败通知等交互性操作
  2. 不支持线程执行先后次序
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 = ; i < ; i++)
{
var worker = new Task(() =>
{
while (true)
{
if (random.Next() % == )
{
if (cts.IsCancellationRequested)
{
break;
} }
else
{
cts.Token.ThrowIfCancellationRequested(); //异常取消
}
Thread.Sleep();
}
});
worker.Start();
worker.ContinueWith(task =>
{
Console.WriteLine("IsCancele={0},IsCompleted={1},IsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
});
} } void Signal()
{
cts.Cancel();
}
}
}
上一篇:SQL Server 解读【已分区索引的特殊指导原则】(2)- 唯一索引分区


下一篇:关于mysql的自增