Console.WriteLine(“取消单个任务”);
//将cts.Token传入任务中,在外部通过控制cts实现对任务的控制
Task.Factory.StartNew(MyTask, cts.Token);
Console.WriteLine("请按回车键停止");
Console.ReadLine();
// cts.Cancel();//传达取消请求
Console.WriteLine("已停止");
Console.ReadLine();
public static void Main(string[] args)
{
DateTime dataTime = DateTime.Now;
string now = dataTime.Month.ToString().PadLeft(2,'0') + dataTime.Day.ToString().PadLeft(2,'0');
string path = string.Format(@"D:\干活\{0}", now);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//再有多个CancellationTokenSource需要并行管理时,比如任意一个任务取消就取消,我们不必一个一个去取消
//可以把并行的CancellationTokenSource组合在一起,一并管理
//定义需要一并管理的cts
Console.WriteLine("=====取消多个任务====");
Task.Factory.StartNew(MyTask1,ctsCombine.Token);
Task.Factory.StartNew(MyTask2, ctsCombine.Token);
Task.Factory.StartNew(MyTask3, ctsCombine.Token);
Console.WriteLine("按回车执行cts1.Cancel()");
Console.ReadLine();
cts1.Cancel();
Console.ReadLine();
}
static void MyTask1()
{
while (!ctsCombine.IsCancellationRequested)
{
Console.WriteLine("MyTask1"+DateTime.Now);
Thread.Sleep(1000);
}
Console.WriteLine("MyTask1已跳出循环" + DateTime.Now);
}
static void MyTask2()
{
while (!ctsCombine.IsCancellationRequested)
{
Console.WriteLine("MyTask2" + DateTime.Now);
Thread.Sleep(1000);
}
Console.WriteLine("MyTask2已跳出循环" + DateTime.Now);
}
static void MyTask3()
{
while (!ctsCombine.IsCancellationRequested)
{
Console.WriteLine("MyTask3" + DateTime.Now);
Thread.Sleep(1000);
}
Console.WriteLine("MyTask3已跳出循环" + DateTime.Now);
}