Task取消以及异常处理

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class TaskCancelTest
    {
        //测试Task取消以及异常处理
        public static void RunTest()
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            ParamCls paramCls = new ParamCls { token = cts.Token, n = 1000 };
            //注意,此处调用多个参数的两种写法:
            Task<Int32> t = new Task<int>(() => OpWithParamIntAndReturnInt(cts.Token, 1000), cts.Token);
            Task<Int32> t1 = new Task<int>(o => OpWithParamIntAndReturnInt2((ParamCls)o), paramCls,cts.Token);

            t.Start();
            //t1.Start();

            //取消任务,这是一个异步操作,Task可能已经完成了
            cts.Cancel();

            try
            {
                //如果任务已经取消了,Result会抛出一个AggregateException
                Console.WriteLine("The result is:"+t.Result.ToString());
            }
            catch(AggregateException ex)
            {
                //将任何的OperationCanceledException对象都视为已处理。
                //其他任何异常都造成抛出一个新的AggregateException,其中只包含未处理的异常。
                ex.Handle(a => a is OperationCanceledException);

                //所有异常都处理好之后,执行下面这一行
                Console.WriteLine("The Task was canceled.");
            }

        }

        private static Int32 OpWithParamIntAndReturnInt(CancellationToken ct, Int32 state)
        {
            Console.WriteLine("In OpWithParamIntAndReturnInt,state=" + state.ToString());

            //在取消标志引用的CancellationTokenSource上,如果调用Cancel,下面这一行会抛出OperationCanceledException
            ct.ThrowIfCancellationRequested();

            Thread.Sleep(1000);
            return state;
        }

        private static Int32 OpWithParamIntAndReturnInt2(ParamCls paramCls)
        {
            Console.WriteLine("In OpWithParamIntAndReturnInt2,state=" + paramCls.n.ToString());

            //在取消标志引用的CancellationTokenSource上,如果调用Cancel,下面这一行会抛出OperationCanceledException
            paramCls.token.ThrowIfCancellationRequested();

            Thread.Sleep(1000);
            return paramCls.n;
        }

        class ParamCls
        {
            public CancellationToken token { get; set; }
            public int n { get; set; }
        }
    }
}

 

posted @ 2020-03-08 22:40  skybirdzw  阅读(706)  评论(0)    收藏  举报