在下面的代码片段中,一个任务使用 TaskCreationOptions.AttachedToParent 创建了两个子任务,这意味着父任务将等待子任务完成。
问题是 - 为什么父任务不返回正确的值 [102]?它是否首先确定其返回值,然后等待子任务完成。如果是这样,那么建立亲子关系的意义何在?
void Main()
{
Console.WriteLine ("Main start.");
int i = 100;
Task<int> t1 = new Task<int>(()=>
{
Console.WriteLine ("In parent start");
Task c1 = Task.Factory.StartNew(() => {
Thread.Sleep(1000);
Interlocked.Increment(ref i);
Console.WriteLine ("In child 1:" + i);
}, TaskCreationOptions.AttachedToParent);
Task c2 = Task.Factory.StartNew(() => {
Thread.Sleep(2000);
Interlocked.Increment(ref i);
Console.WriteLine ("In child 2:" + i);
}, TaskCreationOptions.AttachedToParent );
Console.WriteLine ("In parent end");
return i;
});
t1.Start();
Console.WriteLine ("Calling Result.");
Console.WriteLine (t1.Result);
Console.WriteLine ("Main end.");
}
输出:
Main start.
Calling Result.
In parent start
In parent end
In child 1:101
In child 2:102
100
Main end.