CancellationTokenSource 和 CancellationToken 取消线程

CancellationTokenSource 和 CancellationToken 取消线程

Main 程序[分别调用三个方法]

 static void Main(string[] args)
{
using (CancellationTokenSource cts = new CancellationTokenSource())
{
CancellationToken token = cts.Token;
ThreadPool.QueueUserWorkItem(p => AsyncOperation(token));
Thread.Sleep(TimeSpan.FromSeconds());
cts.Cancel();
}; //休眠两秒,否则主线程结束了,新的线程也会结束
Thread.Sleep(TimeSpan.FromSeconds());
}

方法一

 static void AsyncOperation(CancellationToken token)
{
Console.WriteLine("开始第一个任务");
for (int i = ; i < ; i++)
{
if (token.IsCancellationRequested)
{
Console.WriteLine(i + ":" + token.IsCancellationRequested.ToString());
return;
}
else
{
Console.WriteLine(i + ":" + token.IsCancellationRequested.ToString());
} Thread.Sleep(TimeSpan.FromSeconds());
}
Console.WriteLine("任务执行完成");
}

运行结果

CancellationTokenSource 和 CancellationToken 取消线程

方法二

 static void AsyncOperation2(CancellationToken token)
{
try
{
Console.WriteLine("开始第二个任务");
for (int i = ; i < ; i++)
{
token.ThrowIfCancellationRequested();
Thread.Sleep(TimeSpan.FromSeconds());
Console.WriteLine("第二个任务执行完成");
}
}
catch (OperationCanceledException ex)
{
Console.WriteLine("第二个任务被取消了");
}
}

运行结果:

CancellationTokenSource 和 CancellationToken 取消线程

方法三

  static void AsyncOperation3(CancellationToken token)
{
bool cancelflag = false;
token.Register(() => cancelflag = true);//被取消时cancelflag会设置为True
Console.WriteLine("开始第三个任务");
for (int i = ; i < ; i++)
{
if (cancelflag == true)
{
Console.WriteLine("第三个任务被取消了");
return;
}
else
{
Console.WriteLine(i + ":" + token.IsCancellationRequested.ToString());
}
Thread.Sleep(TimeSpan.FromSeconds());
}
Console.WriteLine("第三个任务执行完成"); }

运行结果:

CancellationTokenSource 和 CancellationToken 取消线程

上一篇:Weblogic的Admin server进程将CPU消耗尽问题解决


下一篇:C. Sequence Transformation