用Task代替TheadPool

时间:2022-11-28 17:15:41

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();
}
}
}