, 작업이 완료 될 때까지 자식 작업을 기다리는 부모 작업을 의미 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.
예 대기 중 및 반환 값은 서로 다르지만 반환 값을 결정하기 전에 기다리지 않는 것이 좋습니다. 이것이 TPL의 버그 일 수 있다고 생각하십니까? – thewpfguy
@thewpfguy 아니요, 분명히 버그는 아닙니다. 첫 번째 작업을 시작한 작업이 첫 번째 작업의 반환 값에 액세스하기 전에 종료 된 경우 작업 결과가 캐싱된다는 것은 자연스러운 결과입니다. –