一、Task類簡介: Task類是在.NET Framework 4.0中提供的新功能,主要用於非同步操作的控制。它比Thread和ThreadPool提供了更為強大的功能,並且更方便使用。 Task和Task<TResult>類:前者接收的是Action委托類型;後者接收的是Func<TResult ...
一、Task類簡介:
Task類是在.NET Framework 4.0中提供的新功能,主要用於非同步操作的控制。它比Thread和ThreadPool提供了更為強大的功能,並且更方便使用。
Task和Task<TResult>類:前者接收的是Action委托類型;後者接收的是Func<TResult>委托類型。
任務Task和線程Thread的區別:
1、任務是架構線上程之上。也就是說任務最終還是要拋給線程去執行,它們都是在同一命名空間System.Threading下。
2、任務跟線程並不是一對一的關係。比如說開啟10個任務並不一定會開啟10個線程,因為使用Task開啟新任務時,是從線程池中調用線程,這點與
ThreadPool.QueueUserWorkItem類似。
二、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:任務工廠
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
三、Task的簡略生命周期
可通過Status屬性獲取。
狀態 | 說明 |
Created | 表示預設初始化任務,但是工廠及Run創建方式會直接跳過。 |
WaitingToRun | 表示等待任務調度器分配線程給任務執行。 |
RanToCompletion | 表示任務執行完畢。 |
四、Task的控制
方法名 | 說明 |
Task.Wait | 如task1.Wait();就是等待task1任務的執行,執行完成後狀態變為Completed。 |
Task.WaitAll | 等待所有的任務執行完畢。 |
Task.WaitAny | 等待任意一個任務完成後就繼續向下執行。 |
Task.ContinueWith | 上一個任務執行完成後自動啟動下一個任務,實現任務的按序進行。 |
CancellationTokenSource | 通過其token來取消一個Task。 |
4.1、組合任務
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.2、串列任務
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); }); //t2、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); }); //等待t2、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.3、子任務
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.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.5、取消任務
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.6、處理單個任務中的異常
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.7、處理多個任務中的異常
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.8、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.9、使用IProgress實現非同步編程的進程通知
IProgress<in T>只提供了一個方法void Report(T value),通過Report方法把一個T類型的值報告給IProgress,然後IProgress<in T>的實現類Progress<in T>的構造函數
接收類型為Action<T>的形參,通過這個委托讓進度顯示在UI界面中。