C#線程學習筆記七:Task詳細用法

    1、Task類簡介:html

    Task類是在.NET Framework 4.0中提供的新功能,主要用於異步操做的控制。它比Thread和ThreadPool提供了更爲強大的功能,而且更方便使用。node

    Task和Task<TResult>類:前者接收的是Action委託類型;後者接收的是Func<TResult>委託類型。編程

    任務Task和線程Thread的區別:架構

    一、任務是架構在線程之上。也就是說任務最終仍是要拋給線程去執行,它們都是在同一命名空間System.Threading下。異步

    二、任務跟線程並非一對一的關係。好比說開啓10個任務並不必定會開啓10個線程,由於使用Task開啓新任務時,是從線程池中調用線程,這點與async

ThreadPool.QueueUserWorkItem相似。ide

    2、Task的建立異步編程

    2.1建立方式1:調用構造函數函數

    class Program
    {
        static void Main(string[] args)
        {
            #region 工做者線程:使用任務實現異步
            ThreadPool.SetMaxThreads(1000, 1000);
            PrintMessage("Main thread start.");
            //調用構造函數建立Task對象
            Task<int> task = new Task<int>(n => AsyncMethod((int)n), 10);

            //啓動任務 
            task.Start();
            //等待任務完成
            task.Wait();
            Console.WriteLine("The method result is: " + task.Result);
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// 打印線程池信息
        /// </summary>
        /// <param name="data"></param>
        private static void PrintMessage(string data)
        {
            //得到線程池中可用的工做者線程數量及I/O線程數量
            ThreadPool.GetAvailableThreads(out int workThreadNumber, out int ioThreadNumber);

            Console.WriteLine("{0}\n CurrentThreadId is:{1}\n CurrentThread is background:{2}\n WorkerThreadNumber is:{3}\n IOThreadNumbers is:{4}\n",
                data,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsBackground.ToString(),
                workThreadNumber.ToString(),
                ioThreadNumber.ToString());
        }

        /// <summary>
        /// 異步方法
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        private static int AsyncMethod(int n)
        {
            Thread.Sleep(1000);
            PrintMessage("Asynchoronous method.");

            int sum = 0;
            for (int i = 1; i < n; i++)
            {
                //運算溢出檢查
                checked
                {
                    sum += i;
                }
            }

            return sum;
        }
    }
View Code

    2.2建立方式2:任務工廠spa

    class Program
    {
        static void Main(string[] args)
        {
            #region 工做者線程:使用任務工廠實現異步
            ////無參無返回值
            //ThreadPool.SetMaxThreads(1000, 1000);
            //Task.Factory.StartNew(() => PrintMessage("Main thread."));
            //Console.Read();

            //有參有返回值
            ThreadPool.SetMaxThreads(1000, 1000);
            PrintMessage("Main thread start.");
            var task = Task.Factory.StartNew(n => AsyncMethod((int)n), 10);
            //等待任務完成
            task.Wait();
            Console.WriteLine("The method result is: " + task.Result);
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// 打印線程池信息
        /// </summary>
        /// <param name="data"></param>
        private static void PrintMessage(string data)
        {
            //得到線程池中可用的工做者線程數量及I/O線程數量
            ThreadPool.GetAvailableThreads(out int workThreadNumber, out int ioThreadNumber);

            Console.WriteLine("{0}\n CurrentThreadId is:{1}\n CurrentThread is background:{2}\n WorkerThreadNumber is:{3}\n IOThreadNumbers is:{4}\n",
                data,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsBackground.ToString(),
                workThreadNumber.ToString(),
                ioThreadNumber.ToString());
        }

        /// <summary>
        /// 異步方法
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        private static int AsyncMethod(int n)
        {
            Thread.Sleep(1000);
            PrintMessage("Asynchoronous method.");

            int sum = 0;
            for (int i = 1; i < n; i++)
            {
                //運算溢出檢查
                checked
                {
                    sum += i;
                }
            }

            return sum;
        }
    }
View Code

    2.3建立方式3:Run方法

    class Program
    {
        static void Main(string[] args)
        {
            #region 工做者線程:使用Task.Run實現異步
            ThreadPool.SetMaxThreads(1000, 1000);
            PrintMessage("Main thread start.");
            var task = Task.Run(() => AsyncMethod(10));
            //等待任務完成
            task.Wait();
            Console.WriteLine("The method result is: " + task.Result);
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// 打印線程池信息
        /// </summary>
        /// <param name="data"></param>
        private static void PrintMessage(string data)
        {
            //得到線程池中可用的工做者線程數量及I/O線程數量
            ThreadPool.GetAvailableThreads(out int workThreadNumber, out int ioThreadNumber);

            Console.WriteLine("{0}\n CurrentThreadId is:{1}\n CurrentThread is background:{2}\n WorkerThreadNumber is:{3}\n IOThreadNumbers is:{4}\n",
                data,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsBackground.ToString(),
                workThreadNumber.ToString(),
                ioThreadNumber.ToString());
        }

        /// <summary>
        /// 異步方法
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        private static int AsyncMethod(int n)
        {
            Thread.Sleep(1000);
            PrintMessage("Asynchoronous method.");

            int sum = 0;
            for (int i = 1; i < n; i++)
            {
                //運算溢出檢查
                checked
                {
                    sum += i;
                }
            }

            return sum;
        }
    }
View Code

    3、Task的簡略生命週期

    可經過Status屬性獲取。

狀態 說明
Created 表示默認初始化任務,可是工廠及Run建立方式會直接跳過。
WaitingToRun 表示等待任務調度器分配線程給任務執行。
RanToCompletion 表示任務執行完畢。

 

 

 

 

 

    4、Task的控制

方法名 說明
Task.Wait 如task1.Wait();就是等待task1任務的執行,執行完成後狀態變爲Completed。
Task.WaitAll 等待全部的任務執行完畢。
Task.WaitAny 等待任意一個任務完成後就繼續向下執行。
Task.ContinueWith 上一個任務執行完成後自動啓動下一個任務,實現任務的按序進行。
CancellationTokenSource 經過其token來取消一個Task。

 

 

 

 

 

 

 

 

    4.一、組合任務

    class Program
    {
        public static void Main()
        {
            #region 工做者線程:Task組合任務
            //建立一個任務
            Task<int> task = new Task<int>(() =>
            {
                int sum = 0;
                Console.WriteLine("使用任務實現異步。");
                for (int i = 0; i < 10; i++)
                {
                    sum += i;
                }
                return sum;
            });
            //任務啓動並安排到任務隊列等待執行(System.Threading.Tasks.TaskScheduler)
            task.Start();
            //任務完成時執行處理
            Task cwt = task.ContinueWith(t =>
            {
                Console.WriteLine("任務的執行結果:{0}", t.Result.ToString());
            });
            task.Wait();
            cwt.Wait();
            Console.ReadLine();
            #endregion
        }
    }
View Code

   運行結果以下:

    4.二、串行任務

    class Program
    {
        public static void Main()
        {
            #region 工做者線程:Task串行任務
            //堆棧
            ConcurrentStack<int> stack = new ConcurrentStack<int>();

            //t1最先串行
            var t1 = Task.Factory.StartNew(() =>
            {
                stack.Push(1);
                stack.Push(2);
            });

            //t二、t3並行執行
            var t2 = t1.ContinueWith(t =>
            {
                stack.TryPop(out int result);
                Console.WriteLine("Task t2 result={0},thread id is {1}.", result, Thread.CurrentThread.ManagedThreadId);
            });
            var t3 = t1.ContinueWith(t =>
            {
                stack.TryPop(out int result);
                Console.WriteLine("Task t3 result={0},thread id is {1}.", result, Thread.CurrentThread.ManagedThreadId);
            });

            //等待t二、t3執行完畢
            Task.WaitAll(t2, t3);

            //t4串行執行
            var t4 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("The stack count={0},thread id is {1}.", stack.Count, Thread.CurrentThread.ManagedThreadId);
            });
            t4.Wait();

            Console.ReadLine();
            #endregion
        }
    }
View Code

    運行結果以下:

    4.三、子任務

    class Program
    {
        public static void Main()
        {
            #region 工做者線程:Task子任務
            Task<string[]> parent = new Task<string[]>(state =>
            {
                Console.WriteLine(state);
                string[] result = new string[2];
                //建立並啓動子任務
                new Task(() => { result[0] = "子任務1。"; }, TaskCreationOptions.AttachedToParent).Start();
                new Task(() => { result[1] = "子任務2。"; }, TaskCreationOptions.AttachedToParent).Start();
                return result;
            }, "我是父任務,我建立了2個子任務,它們執行完後我纔會結束執行。");
            //任務完成時執行處理
            parent.ContinueWith(t =>
            {
                Array.ForEach(t.Result, r => Console.WriteLine(r));
            });
            //啓動父任務
            parent.Start();
            parent.Wait();
            Console.ReadLine();
            #endregion
        }
    }
View Code

    運行結果以下:

    4.四、動態並行任務

    /// <summary>
    /// 結點類
    /// </summary>
    class Node
    {
        public Node Left { get; set; }
        public Node Right { get; set; }
        public string Text { get; set; }
    }

    class Program
    {
        public static void Main()
        {
            #region 工做者線程:Task動態並行任務
            Node root = GetNode();
            DisplayTree(root);
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// GetNode方法
        /// </summary>
        /// <returns></returns>
        static Node GetNode()
        {
            Node root = new Node
            {
                Left = new Node
                {
                    Left = new Node
                    {
                        Text = "L-L"
                    },
                    Right = new Node
                    {
                        Text = "L-R"
                    },
                    Text = "L"
                },
                Right = new Node
                {
                    Left = new Node
                    {
                        Text = "R-L"
                    },
                    Right = new Node
                    {
                        Text = "R-R"
                    },
                    Text = "R"
                },
                Text = "Root"
            };
            return root;
        }

        /// <summary>
        /// DisplayTree方法
        /// </summary>
        /// <param name="root"></param>
        static void DisplayTree(Node root)
        {
            var task = Task.Factory.StartNew
                (
                    () =>
                    DisplayNode(root),
                    CancellationToken.None,
                    TaskCreationOptions.None,
                    TaskScheduler.Default
                );
            task.Wait();
        }

        /// <summary>
        /// DisplayNode方法
        /// </summary>
        /// <param name="current"></param>
        static void DisplayNode(Node current)
        {

            if (current.Left != null)
            {
                Task.Factory.StartNew
                    (
                        () =>
                        DisplayNode(current.Left),
                        CancellationToken.None,
                        TaskCreationOptions.AttachedToParent,
                        TaskScheduler.Default
                    );
            }
            if (current.Right != null)
            {
                Task.Factory.StartNew
                    (
                        () =>
                        DisplayNode(current.Right),
                        CancellationToken.None,
                        TaskCreationOptions.AttachedToParent,
                        TaskScheduler.Default
                    );
                Console.WriteLine("The current node text={0},thread id is {1}.", current.Text, Thread.CurrentThread.ManagedThreadId);
            }
        }
    }
View Code

    運行結果以下:

    4.五、取消任務

    class Program
    {
        static void Main(string[] args)
        {
            #region 取消任務
            ThreadPool.SetMaxThreads(1000, 1000);
            PrintMessage("Main thread start.");
            CancellationTokenSource cts = new CancellationTokenSource();

            //調用構造函數建立Task對象,將一個CancellationToken傳給Task構造器從而使Task和CancellationToken關聯起來。
            Task<int> task = new Task<int>(n => AsyncMethod(cts.Token, (int)n), 10);

            //啓動任務 
            task.Start();
            //延遲取消任務
            Thread.Sleep(3000);

            //取消任務
            cts.Cancel();
            Console.WriteLine("The method result is: " + task.Result);
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// 打印線程池信息
        /// </summary>
        /// <param name="data"></param>
        private static void PrintMessage(string data)
        {
            //得到線程池中可用的工做者線程數量及I/O線程數量
            ThreadPool.GetAvailableThreads(out int workThreadNumber, out int ioThreadNumber);

            Console.WriteLine("{0}\n CurrentThreadId is:{1}\n CurrentThread is background:{2}\n WorkerThreadNumber is:{3}\n IOThreadNumbers is:{4}\n",
                data,
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsBackground.ToString(),
                workThreadNumber.ToString(),
                ioThreadNumber.ToString());
        }

        /// <summary>
        /// 異步方法
        /// </summary>
        /// <param name="ct"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        private static int AsyncMethod(CancellationToken ct, int n)
        {
            Thread.Sleep(1000);
            PrintMessage("Asynchoronous method.");

            int sum = 0;
            try
            {
                for (int i = 1; i < n; i++)
                {
                    //當CancellationTokenSource對象調用Cancel方法時,就會引發OperationCanceledException異常,
                    //經過調用CancellationToken的ThrowIfCancellationRequested方法來定時檢查操做是否已經取消,
                    //這個方法和CancellationToken的IsCancellationRequested屬性相似。
                    ct.ThrowIfCancellationRequested();
                    Thread.Sleep(500);
                    //運算溢出檢查
                    checked
                    {
                        sum += i;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception is:" + e.GetType().Name);
                Console.WriteLine("Operation is canceled.");
            }

            return sum;
        }
    }
View Code

    運行結果以下:

    4.六、處理單個任務中的異常

    class Program
    {
        public static void Main()
        {
            #region 工做者線程:處理單個任務中的異常
            try
            {
                Task<int> task = Task.Run(() => SingleTaskExceptionMethod("Single task.", 2));
                int result = task.GetAwaiter().GetResult();
                Console.WriteLine("Result:{0}", result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Single task exception caught:{0}", ex.Message);
            }
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// SingleTaskException方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="seconds"></param>
        /// <returns></returns>
        static int SingleTaskExceptionMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on thread {1}.Is it threadpool thread?:{2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            throw new Exception("Boom.");
        }
    }
View Code

    運行結果以下:

    4.七、處理多個任務中的異常

    class Program
    {
        public static void Main()
        {
            #region 工做者線程:處理多個任務中的異常
            try
            {
                var t1 = new Task<int>(() => MultipleTaskExceptionMethod("Multiple task 1", 3));
                var t2 = new Task<int>(() => MultipleTaskExceptionMethod("Multiple task 2", 2));
                var complexTask = Task.WhenAll(t1, t2);
                var exceptionHandler = complexTask.ContinueWith
                    (
                        t =>
                        Console.WriteLine("Result:{0}", t.Result),
                        TaskContinuationOptions.OnlyOnFaulted
                    );
                t1.Start();
                t2.Start();
                Task.WaitAll(t1, t2);
                Console.ReadLine();
            }
            catch (AggregateException ex)
            {
                ex.Handle
                    (
                        exception =>
                        {
                            Console.WriteLine(exception.Message);
                            return true;
                        }
                    );
            }
            #endregion
        }

        /// <summary>
        /// MultipleTaskException方法
        /// </summary>
        /// <param name="name"></param>
        /// <param name="seconds"></param>
        /// <returns></returns>
        static int MultipleTaskExceptionMethod(string name, int seconds)
        {
            Console.WriteLine("Task {0} is running on thread id {1}. Is it threadpool thread?:{2}",
                name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            throw new Exception(string.Format("Task {0} Boom.", name));
        }
    }
View Code

    運行結果以下:

    4.八、Task.FromResult的應用

    class Program
    {
        //字典
        private static readonly IDictionary<string, string> cache = new Dictionary<string, string>()
        {
            {"0001","A"},
            {"0002","B"},
            {"0003","C"},
            {"0004","D"},
            {"0005","E"},
            {"0006","F"},
        };

        public static void Main()
        {
            #region 工做者線程:Task.FromResult的應用
            Task<string> task = GetValueFromCacheMethod("0006");
            Console.WriteLine("Result={0}", task.Result.ToString());
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// GetValueFromCache方法
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private static Task<string> GetValueFromCacheMethod(string key)
        {
            Console.WriteLine("GetValueFromCache開始執行……");
            string result = string.Empty;
            Thread.Sleep(3000);
            Console.WriteLine("GetValueFromCache繼續執行……");
            if (cache.TryGetValue(key, out result))
            {
                return Task.FromResult(result);
            }
            return Task.FromResult("");
        }
    }
View Code

    運行結果以下:

    4.九、使用IProgress實現異步編程的進程通知

    IProgress<in T>只提供了一個方法void Report(T value),經過Report方法把一個T類型的值報告給IProgress,而後IProgress<in T>的實現類Progress<in T>的構造函數

接收類型爲Action<T>的形參,經過這個委託讓進度顯示在UI界面中。

    class Program
    {
        public static void Main()
        {
            #region 工做者線程:使用IProgress實現異步編程的進程通知
            Task task = Display();
            task.Wait();
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// DoProcessing方法
        /// </summary>
        /// <param name="progress"></param>
        static void DoProcessing(IProgress<int> progress)
        {
            for (int i = 1; i <= 100; i++)
            {
                Thread.Sleep(100);
                if (progress != null)
                {
                    progress.Report(i);
                }
            }
        }

        /// <summary>
        /// Display方法
        /// </summary>
        /// <returns></returns>
        static async Task Display()
        {
            //當前線程
            var progress = new Progress<int>
                (
                    percent =>
                    {
                        Console.Clear();
                        Console.Write("{0}%", percent);
                    }
                );
            //線程池線程
            await Task.Run(() => DoProcessing(progress));
            Console.WriteLine("");
            Console.WriteLine("結束");
        }
    }
View Code

    運行結果以下:

    4.十、Factory.FromAsync的應用

    (簡APM模式(委託)轉換爲任務)(BeginXXX和EndXXX)

    帶回調方式:

    class Program
    {
        //使用委託實現異步,是使用了異步編程模型APM。
        private delegate string AsynchronousTask(string threadName);

        public static void Main()
        {
            #region 工做者線程:帶回調方式的Factory.FromAsync的應用
            AsynchronousTask d = TestMethod;
            Console.WriteLine("Option 1");
            Task<string> task = Task<string>.Factory.FromAsync(d.BeginInvoke("AsyncTaskThread", Callback, "A delegate asynchronous called."), d.EndInvoke);

            task.ContinueWith(t => Console.WriteLine("Callback is finished,now running a continuation. Result: {0}",t.Result));

            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// FromAsync方法
        /// </summary>
        /// <param name="threadName"></param>
        /// <returns></returns>
        private static string FromAsyncMethod(string threadName)
        {
            Console.WriteLine("Starting...");
            Console.WriteLine("Is it threadpool thread?:{0}", Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Thread.CurrentThread.Name = threadName;
            return string.Format("Thread name:{0}", Thread.CurrentThread.Name);
        }

        /// <summary>
        /// Callback方法
        /// </summary>
        /// <param name="ar"></param>
        private static void Callback(IAsyncResult ar)
        {
            Console.WriteLine("Starting a callback...");
            Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState);
            Console.WriteLine("Is it threadpool thread?:{0}", Thread.CurrentThread.IsThreadPoolThread);
            Console.WriteLine("Threadpool worker thread id: {0}",Thread.CurrentThread.ManagedThreadId);
        }
    }
View Code

    運行結果以下:

    不帶回調方式:

    class Program
    {
        //使用委託實現異步,是使用了異步編程模型APM。
        private delegate string AsynchronousTask(string threadName);

        public static void Main()
        {
            #region 工做者線程:不帶回調方式的Factory.FromAsync的應用
            AsynchronousTask d = FromAsyncMethod;
            Task<string> task = Task<string>.Factory.FromAsync(d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "A delegate asynchronous called.");
            task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}",t.Result));
            while (!task.IsCompleted)
            {
                Console.WriteLine(task.Status);
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
            Console.WriteLine(task.Status);
            Console.ReadLine();
            #endregion
        }

        /// <summary>
        /// FromAsync方法
        /// </summary>
        /// <param name="threadName"></param>
        /// <returns></returns>
        private static string FromAsyncMethod(string threadName)
        {
            Console.WriteLine("Starting...");
            Console.WriteLine("Is it threadpool thread?:{0}", Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Thread.CurrentThread.Name = threadName;
            return string.Format("Thread name:{0}", Thread.CurrentThread.Name);
        }
    }
View Code

    運行結果以下:

 

    參考自:

    http://www.javashuo.com/article/p-apcuhyet-bm.html

    http://www.javashuo.com/article/p-vwprltbu-bd.html

相關文章
相關標籤/搜索