Task浅析

Task是.net 4.0中的一个新特性,提供的功能非常强大,下面是其具体的使用方法演示:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            RunnerRaceTest();

            Console.WriteLine("into main loop now...");
            Console.ReadLine();
        }

        static void RunnerRaceTest()
        {
            Task[] tRunners = new Task[10];
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("我是运动员" + i.ToString() + "号,我已经就位");
                tRunners[i] = new Task(() => { });
            }

            Console.WriteLine("预备开始,跑...");
            Parallel.ForEach(tRunners, i => 
            {
                i.Start();
                Thread.Sleep(2000);
                Console.WriteLine(i.Id.ToString() + "号运动员已经到达...");
            });

            Task.WaitAll(tRunners);
            Console.WriteLine("比赛完毕...");
        }

        //handle ContinueWith method. 
        //TaskContinuationOptions.OnlyOnRanToCompletion means that 
        //only the first task runs successfully, then the continue one will start to run.
        //ContinueWith的使用方法
        /*******运行结果(当第一个TaskContinuationOptions.OnlyOnRanToCompletion时)*********
         *  this is an exception
         *  into main loop now...
         **********************/
        /*******运行结果(当第一个TaskContinuationOptions.OnlyOnFaulted时)*********
          * exception found in prev task when handling Continuation...
          * this is continuation...
          * this is an exception
          * into main loop now...
         **********************/
        static void TaskContinueWith()
        {
            Task t1 = new Task(() =>
            {
                throw new Exception("this is an exception");
                Console.WriteLine("this is task one...");
            });

            Task t2 = t1.ContinueWith((preTask) =>
            {
                if (preTask.Exception != null)
                {
                    Console.WriteLine("exception found in prev task when handling Continuation...");
                }
                Console.WriteLine("this is continuation...");
            },TaskContinuationOptions.AttachedToParent|TaskContinuationOptions.OnlyOnFaulted);

            t1.Start();

            try
            {
                t1.Wait();
                t2.Wait();
            }
            catch (AggregateException e)
            {
                Console.WriteLine(e.InnerException.Message);
            }
        }

        //handle children tasks
        //主要是用来测试子任务的运行,利用AttachedToParent来实现子任务功能
        /*******运行结果*********
         * into the first task now...
         * into the second task now...
         * into the third task now...
         * Exception caught :GrandChild exception
         * into main loop now...
         **********************/
        static void TaskWithChildren()
        {
            Task t = new Task(() => //主任务
            {
                Console.WriteLine("into the first task now...");
                Task childTask = new Task(() =>  //第一个子任务
                {
                    Console.WriteLine("into the second task now...");
                    Task grandChildTask = new Task(() => //第二个子任务
                    {
                        Console.WriteLine("into the third task now...");
                        throw new Exception("GrandChild exception");
                    }, TaskCreationOptions.AttachedToParent);
                    grandChildTask.Start(); //开始第二个子任务

                }, TaskCreationOptions.AttachedToParent);
                childTask.Start(); //开始第一个子任务
            });

            t.Start(); //开启主任务

            try
            {
                t.Wait(); //同步运行等待
            }
            catch (AggregateException e)
            {
                Console.WriteLine("Exception caught : " + e.InnerException.InnerException.InnerException.Message);
            }
        }

        //handle cancellation during task running
        //主要用来测试任务执行过程中的取消操作
        /*******运行结果*********
         * this is task iteration 1
         * the operation has been canceled...
         * into main loop now...
        **********************/
        static void TaskWithCancellation()
        {
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();  
            CancellationToken cancellationToken = cancellationTokenSource.Token;  //主要用于任务取消操作的信号量设置

            Task t = new Task(() =>
            {
                int i = 0;
                while (true)
                {
                    i++;
                    Thread.Sleep(1000);
                    Console.WriteLine("this is task iteration " + i);

                    cancellationToken.ThrowIfCancellationRequested(); //注册信号量,如果用户取消,那么将会中断在此处
                    Console.WriteLine("Test to see if below can be excuted...");
                    Console.WriteLine("I am not excute");
                }
            }, cancellationToken);

            t.Start();  //开始任务

            Thread.Sleep(1000);

            cancellationTokenSource.Cancel(); //取消任务

            try
            {
                t.Wait();
            }
            catch (AggregateException e)
            {
                if (e.InnerException is OperationCanceledException)
                    Console.WriteLine("the opeartion has been canceled...");
                else
                    Console.WriteLine("encounter some unexpected exceptions...");
            }
        }

        //handle timeout in task running
        //主要是用来测试任务执行的超时功能
        /*******运行结果*********
         * We are waiting for the task to finish
         * the task has timed out.
         * into main loop now...
         * I started...
        * *********************/
        static void TaskWithTimeout()
        {
            Task t = new Task(() => 
            {
                Thread.Sleep(3000);  
                Console.WriteLine("I started...");
            });

            t.Start();  //开始任务
            Console.WriteLine("We are waiting for the task to finish");

            //任务执行的超时时间为2s,程序执行需要3s,所以会出现超时
            bool hasNotTimeOut = t.Wait(2000); 

            if (hasNotTimeOut)
                Console.WriteLine("the task has not  timed out.");
            else
                Console.WriteLine("the task has timed out.");

        }

        //handle exception during task execution.
        //主要是用来测试任务执行时候的错误捕获功能
        /*******运行结果*********
        * We are waiting for the task to finish
        * Caught Exception:this is exception in task...
        * into main loop now...
        * *********************/
        static void TaskWithException()
        {
            Task t = new Task(() =>
            {
                throw new Exception("this is exception in task...");  //当任务执行的时候,出现了Exception
                Console.WriteLine("I started..");
            });

            t.Start();  //开始运行任务

            Console.WriteLine("We are waiting for the task to finish"); 

            try
            {
                t.Wait();  //同步执行
            }
            catch (AggregateException e)  //AggregateException可以捕获运行中出现的错误
            {
                Console.WriteLine("Caught Exception:" + e.InnerException.Message); //这里显示
            }
        }

        //simple use of Task
        //主要是介绍Task的最简单用法
        /*******运行结果*********
         *  started...
         * into main loop now...
         * *********************/
        static void TaskOfFirst()
        {
            Task t = new Task(() => {
                Console.WriteLine("I started...");
            });

            //开始运行
            t.Start();
            //等待任务运行完成,这里将会阻塞主线程,如果去掉,那么主线程和子线程会并行运行
            t.Wait();  
        }
    }
}
原文地址:https://www.cnblogs.com/scy251147/p/2843875.html