I'm not too familiar with TPL, but isn't this what ContinueWhenAll
is for?
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 Task.Factory.ContinueWhenAll(
new[] { second, third },
(twotasks) => /* not sure how to get the original result here */);
}
I don't know how to get main
's result from the completed second
and third
(contained in twotasks
), but maybe you can modify them to pass through the result.
Edit: Or, as Alex points out, use
Task.Factory.ContinueWhenAll(new[] { main, second, third }, (threetasks) => ...
and read the result from threetasks[0]
.