开发者

CancellationTokenSource.Cancel(false)

    static void Main(string[] args)
    {
        CancellationTokenSource cts = new CancellationTokenSource();

        ThreadPool.QueueUserWorkItem(o => DoWork(cts.Token, 100));

        Thread.Sleep(500);

        try
        {
            cts.Token.Register(CancelCallback3);
            cts.Token.Register(CancelCallback2);
            cts.Token.Register(CancelCallback1);



            cts.Cancel(false);
        }
        catch (AggregateException ex)
        {
            foreach (Exception curEx in ex.Data)
            {
                Trace.WriteLine(curEx.ToString());    
            }

        }

        Console.ReadKey();
    }

    private static void CancelCallback1()
    {
        Trace.WriteLine("CancelCallback1 was called");
        throw new Exception("CancellCallback1 exception");
    }


    private static void CancelCallback2()
    {
        Trace.WriteLine("CancelCallback2 was called");
        throw new Exception("CancellCallback2 exception");
    }

    private static void CancelCallback3()
    {
        Trace.WriteLine("CancelCallback3 was called");
    }

    private static void DoWork(CancellationToken cancellationToken, int maxLength)
    {
        int i = 0;
        while (i < maxLength && !cancellationToken.IsCancellationRequested)
        {
            Trace.WriteLine(i++);
            Thread.Sleep(100);
        }
    }

The output is:

开发者_高级运维0
1
2
3
4
CancelCallback1 was called

According to http://msdn.microsoft.com/en-us/library/dd321703.aspx I expected to get AggregateException, it looks like that throwOnFirstException parameter doesn't make any sense here. What's wrong with my code.


You need to use the Task<> class to get an AggregateException. It is a substitute for ThreadPool.QueueUserWorkItem().


The problem is with lack of strong debugging experience in Visual Studio. My VS debugger settings were set to stop at first exception occurence.

FYI CancellationTokenSource.Cancel(false) works fine with ThreadPool as well as with Tasks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜