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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM