0

I can't handle an OperationCanceledException in my code. I'm trying to cancel a Task, and if I cancel it immediately after its creation everything goes fine, but when I add line Thread.Sleep(2000); to wait some time before canceling I get unhandled exception.

class TaskCancelationDemo
{
    static void Main()
    {
        Console.WriteLine("Main thread is started");

        CancellationTokenSource cancelTokSrc = new CancellationTokenSource();
        var ct = cancelTokSrc.Token;
        Task myTask = Task.Factory.StartNew(MyTask, cancelTokSrc.Token, cancelTokSrc.Token);
        Thread.Sleep(2000);
        try
        {
            cancelTokSrc.Cancel();
            myTask.Wait();
        }
        catch (AggregateException a)
        {
            if (myTask.IsCanceled)
            {
                Console.WriteLine("Task was canceled");
            }
        }
        catch (Exception e) { }
        Console.ReadKey();
    }

    static void MyTask(Object ct)
    {
        CancellationToken calcelTok = (CancellationToken)ct;

        calcelTok.ThrowIfCancellationRequested();

        Console.WriteLine("MyTask() is started");

        for (int count = 0; count < 10; count++)
        {
            if (calcelTok.IsCancellationRequested)
            {
                Console.WriteLine("Get a cancelation request");
                calcelTok.ThrowIfCancellationRequested();
            }
            else
            {
                Thread.Sleep(500);
                Console.WriteLine("Count : " + count);
            }
        }
        Console.WriteLine("MyTask is finished");
    }

}
tashuhka
  • 5,028
  • 4
  • 45
  • 64
Arsen
  • 23
  • 3
  • What is the exception message? – Yuval Itzchakov Aug 25 '14 at 13:07
  • 1
    "I get unhandled exception", and the unhandled exception you get is? – Scott Chamberlain Aug 25 '14 at 13:08
  • Thanks for answering, I've found the solution. It was problem with settings in my visual studio. If I press "Step over", everything goes fine again. I mean exception message appears, programm flow pauses, but I can continue it and programm ends successfully. – Arsen Aug 25 '14 at 13:16
  • I copy pasted this code into VS and it works as expected, an `AggregateException` is what gets thrown. – Yuval Itzchakov Aug 25 '14 at 13:17
  • AggregateException used to be thrown after myTask.Wait(); But in previous case programm flow was paused before it. And OperationCanceledException was thrown at the line cancelTokSrc.Cancel();. – Arsen Aug 25 '14 at 13:20

0 Answers0