如果我有以下代码
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static Task<int> GetSuperLargeNumber()
{
var main = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
return 100;
});
var second = main.ContinueWith(x => Console.WriteLine("Second: " + x.Result), TaskContinuationOptions.AttachedToParent);
var third = main.ContinueWith(x => Console.WriteLine("Third: " + x.Result), TaskContinuationOptions.AttachedToParent);
return main.ContinueWith(x =>
{
Task.WaitAll(second, third);
return x.Result;
});
}
static void Main(string[] args)
{
GetSuperLargeNumber().ContinueWith(x => Console.WriteLine("Complete"));
Console.ReadKey();
}
}
}
我希望 main 首先启动,然后 2 个依赖项可以在第一个和第二个并行启动之后启动。然后我想返回一个带有值的未来,供调用者添加一个延续。但是我想确保第二个和第三个先运行。下面的代码是实现这一目标的最佳方法吗?看起来有点笨重