Task.IsCancelled doesn't work

大城市里の小女人 提交于 2019-12-24 01:39:09

问题


I've got the following sample code:

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

The output is:

  • Task: Running
  • Main: Cancel
  • Main: Wait
  • Task: ThrowIfCancellationRequested
  • Task: OperationCanceledException
  • ContinueWith: cts.IsCancellationRequested = True, task.IsCanceled = False, task.Exception = AggregateException
  • Main: task.IsCanceled = False
  • Press any key to exit...

If I remove ContinueWith, then the output is:

  • Task: Running
  • Main: Cancel
  • Main: Wait
  • Task: ThrowIfCancellationRequested
  • Task: OperationCanceledException
  • Main: Catch AggregateException
  • Main: task.IsCanceled = False
  • Press any key to exit...

I don't understand, why task.IsCanceled returns false in both cases?

And why exception is rethrown only without ContinueWith?


What I'm trying to achieve is an uniform and simple way for waiting for task completion and a property that will indicate if task was cancelled or not.


回答1:


I think you are not cancelling the task itself, but just throwing an exception from a task. Try using StartNew(Action action,CancellationToken cancellationToken) instead of StartNew(Action action). You can also add cancellation token as a parameter to ContinueWith.



来源:https://stackoverflow.com/questions/15384237/task-iscancelled-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!