gpt4 book ai didi

c# - Task.IsCancelled 不起作用

转载 作者:行者123 更新时间:2023-12-03 22:49:46 26 4
gpt4 key购买 nike

我有以下示例代码:

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

输出是:

  • 任务:运行
  • 主要:取消
  • 主要:WAITING
  • 任务:ThrowIfCancellationRequested
  • 任务:OperationCanceledException
  • ContinueWith:cts.IsCancellationRequested = True,task.IsCanceled = False,task.Exception = AggregateException
  • 主要:task.IsCanceled = False
  • 按任意键退出...

如果我删除 ContinueWith,则输出为:

  • 任务:运行
  • 主要:取消
  • 主要:WAITING
  • 任务:ThrowIfCancellationRequested
  • 任务:OperationCanceledException
  • 主要:捕获 AggregateException
  • 主要:task.IsCanceled = False
  • 按任意键退出...

我不明白,为什么 task.IsCanceled 在这两种情况下都返回 false?

为什么只在没有 ContinueWith 的情况下重新抛出异常?


我想要实现的是一种统一且简单的等待任务完成的方法,以及一个指示任务是否被取消的属性。

最佳答案

我认为您并没有取消任务本身,而只是从任务中抛出异常。尝试使用 StartNew (Action action,CancellationToken cancellationToken) 而不是 StartNew(Action action)。您还可以将取消标记作为参数添加到 ContinueWith。

关于c# - Task.IsCancelled 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15384237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com