据我了解,ContinueWith 方法等待相关任务完成。我是以下代码的情况,这意味着它在完成子任务时完成。如果这是真的,为什么它有时会输出 0 0 0 而有时会输出 0 1 2?
static void Main(string[] args)
{
Task<Int32[]> parent = Task.Run(() =>
{
var results = new Int32[3];
new Task(() => results[0] = 0, TaskCreationOptions.AttachedToParent).Start();
new Task(() => results[1] = 1, TaskCreationOptions.AttachedToParent).Start();
new Task(() => results[2] = 2, TaskCreationOptions.AttachedToParent).Start();
return results;
});
var finalTask = parent.ContinueWith(n =>
{
foreach (Int32 i in n.Result)
Console.WriteLine(i);
});
finalTask.Wait();
Console.ReadLine();
}