Task.Factory.StartNew传递返回值

时间:2014-11-20 14:46:39

标签: c# task

我使用下面的方法,我想传递dosleep方法的返回值:

static void Main(string[] args)
{
    var t1 = Task.Factory.StartNew(() => dosleep(2000));
    var t2 = Task.Factory.StartNew(() => dosleep(1000));
    Task.WaitAll(t1,t2);
    Console.WriteLine("All Done in {0} milliseconds!"); //t1+t2 here!!
}

public static int dosleep(int Milliseconds)
{
    System.Threading.Thread.Sleep(Milliseconds);
    Console.WriteLine("Task finished");
    return Milliseconds;
}

1 个答案:

答案 0 :(得分:5)

使用Task对象的Result属性

Console.WriteLine("All Done in {0} milliseconds!", t1.Result + t2.Result);