using System;
using System.Threading;
using System.Threading.Tasks;
using static System.Console;
namespace 取消类的使用
{
class Program
{
static void Main(string[] args)
{
//根据随机数判断当前任务的是完成还是取消还是异常。
var 取消类实例 = new CancellationTokenSource();
var 随机数 = new Random().Next(100);
var 任务 = Task.Factory.StartNew(() =>
{
//等待取消随机数验证
Thread.Sleep(1000);
取消类实例.Token.ThrowIfCancellationRequested();//验证任务是否取消 取消就抛出异常
if (随机数 > 67)
{
return "任务完成";
}
else
{
throw new Exception("任务异常");
}
});
回调方法(任务);
if (随机数 <= 33)
{
取消类实例.Cancel();
}
ReadLine();
}
static void 回调方法(Task<string> t)
{
//给任务添加接续任务,
//完成
t.ContinueWith(x =>
{
WriteLine(x.Result);
}, TaskContinuationOptions.OnlyOnRanToCompletion);
//取消
t.ContinueWith(x =>
{
WriteLine("任务取消");
}, TaskContinuationOptions.OnlyOnCanceled);
//异常
t.ContinueWith(x =>
{
foreach (var item in x.Exception.InnerExceptions)
{
WriteLine(item.Message);
}
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
}
C# CancellationTokenSource类的简单使用
最新推荐文章于 2024-07-29 13:46:39 发布