的任务.IsCancelled不起作用
本文关键字:不起作用 IsCancelled 任务 | 更新日期: 2023-09-27 18:03:45
我有以下示例代码:
static class Program
{
static void Main()
{
var cts = new CancellationTokenSource();
var task = Task.Factory.StartNew(
() =>
{
try
{
Console.WriteLine("Task: Running");
Thread.Sleep(5000);
Console.WriteLine("Task: ThrowIfCancellationRequested");
cts.Token.ThrowIfCancellationRequested();
Thread.Sleep(2000);
Console.WriteLine("Task: Completed");
}
catch (Exception exception)
{
Console.WriteLine("Task: " + exception.GetType().Name);
throw;
}
}).ContinueWith(t => Console.WriteLine("ContinueWith: cts.IsCancellationRequested = {0}, task.IsCanceled = {1}, task.Exception = {2}", cts.IsCancellationRequested, t.IsCanceled, t.Exception == null ? "null" : t.Exception.GetType().Name));
Thread.Sleep(1000);
Console.WriteLine("Main: Cancel");
cts.Cancel();
try
{
Console.WriteLine("Main: Wait");
task.Wait();
}
catch (Exception exception)
{
Console.WriteLine("Main: Catch " + exception.GetType().Name);
}
Console.WriteLine("Main: task.IsCanceled = {0}", task.IsCanceled);
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
输出为:
- <
- 任务:运行/gh>
- 主要:取消
- 主要:等
- 任务:ThrowIfCancellationRequested
- 任务:OperationCanceledException
- ContinueWith: cts。IsCancellationRequested = True,任务。IsCanceled = False,任务。Exception = AggregateException
- :主要任务。IsCanceled = False
- 按任意键退出…
如果我删除ContinueWith,那么输出是:
- <
- 任务:运行/gh>
- 主要:取消
- 主要:等
- 任务:ThrowIfCancellationRequested
- 任务:OperationCanceledException
- Main: Catch AggregateException
- :主要任务。IsCanceled = False
- 按任意键退出…
我不明白,为什么任务。IsCanceled在两种情况下都返回false ?
为什么只在没有ContinueWith的情况下才重新抛出异常?
我想要实现的是一个统一和简单的方式来等待任务完成和一个属性,将表明任务是否被取消。
我认为你没有取消任务本身,而只是从任务抛出一个异常。尝试使用StartNew(Action Action,CancellationToken CancellationToken)代替StartNew(Action Action)。您还可以添加取消令牌作为ContinueWith的参数。