C# Task的使用---任務的結果


任務結束時,它可以把一些有用的狀態信息寫到共享對象中。這個共享對象必須是線程安全的。另一個選項是使用返回某個結果的任務。使用Task類的泛型版本,就可以定義返回某個結果的任務的返回類型。

為了返回某個結果任務調用的方法可以聲明為帶任意返回類型。示例方法TaskWithResult()利用一個元組返回兩個int值。該方法的輸入可以是void或object類型,如下所示:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.Threading;
   6: using System.Threading.Tasks;
   7: namespace TaskSamples   
   8: {
   9:     class Program
  10:     {
  11:         static Tuple<int, int> TaskWithResult(object division)
  12:         {
  13:             Tuple<int, int> div = (Tuple<int, int>)division;
  14:             int result = div.Item1 / div.Item2;
  15:             int reminder = div.Item1 % div.Item2;
  16:             Console.WriteLine("task creates a result...");
  17:             return Tuple.Create<int, int>(result, reminder);
  18:         }
  19:  
  20:         static void Main(string[] args)
  21:         {   //定義一個調用TaskWithResult()方法的任務時,要使用泛型類Task<TResult>.泛型參數定義了返回類型。通過構造函數,把這個方法傳遞給Func委托,第二個參數定義了輸入值。因為這個任務在object參數中需要兩個輸入值,所以還創建了一個元組。Task實例t1的Result屬性被禁用,並一直等到該任務完成。任務完成后,Result屬性包含任務的結果。
  22:             var t1 = new Task<Tuple<int, int>>(TaskWithResult, Tuple.Create<int, int>(8, 3));
  23:             t1.Start();
  24:             Console.WriteLine(t1.Result);
  25:             t1.Wait();
  26:             Console.WriteLine("result from task:{0},{1}", t1.Result.Item1, t1.Result.Item2);
  27:             Console.ReadKey();
  28:         }
  29:     }
  30: }

 

該示例運行結果如下所示:

image


免責聲明!

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



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