任务结束时,它可以把一些有用的状态信息写到共享对象中。这个共享对象必须是线程安全的。另一个选项是使用返回某个结果的任务。使用Task类的泛型版本,就可以定义返回某个结果的任务的返回类型。
为了返回某个结果任务调用的方法可以声明为带任意返回类型。示例方法TaskWithResult()利用一个元组返回两个int值。该方法的输入可以是void或object类型,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TaskSamples
8: {
class Program
10: {
object division)
12: {
int>)division;
int result = div.Item1 / div.Item2;
int reminder = div.Item1 % div.Item2;
);
int>(result, reminder);
18: }
19:
string[] args)
21: { //定义一个调用TaskWithResult()方法的任务时,要使用泛型类Task<TResult>.泛型参数定义了返回类型。通过构造函数,把这个方法传递给Func委托,第二个参数定义了输入值。因为这个任务在object参数中需要两个输入值,所以还创建了一个元组。Task实例t1的Result属性被禁用,并一直等到该任务完成。任务完成后,Result属性包含任务的结果。
int>(8, 3));
23: t1.Start();
24: Console.WriteLine(t1.Result);
25: t1.Wait();
, t1.Result.Item1, t1.Result.Item2);
27: Console.ReadKey();
28: }
29: }
30: }
该示例运行结果如下所示: