任务取消c#。无法处理异常

时间:2014-08-25 13:03:43

标签: c# .net multithreading task

我无法在代码中处理OperationCanceledException。我试图取消一个任务,如果我在创建后立即取消它一切都很顺利,但是当我添加行Thread.Sleep(2000);等待一段时间才取消之前我得到了未处理的异常。

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

}

0 个答案:

没有答案