Example
static void Main(string[] args)
{
Task<Int32[]> parent = new Task<Int32[]>(() =>
{
var results = new Int32[3];
StartNewTask(results, 0, 1);
StartNewTask(results, 1, 2);
StartNewTask(results, 2, 3);
return results;
});
parent.ContinueWith(parentTask => Array.ForEach(parentTask.Result, Console.WriteLine));
parent.Start();
Thread.Sleep(3000);
}
static void StartNewTask(Int32[] results, int index, int value)
{
new Task(() => results[index] = value, TaskCreationOptions.AttachedToParent).Start();
}
output
1
2
3
TASK FACTORY
static void Main(string[] args)
{
Task parent = new Task(() =>
{
var cts = new CancellationTokenSource();
// create params for tasks in one place
var tf = new TaskFactory<int>(
cts.Token,
TaskCreationOptions.AttachedToParent,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default
);
var childTasks = new[]
{
tf.StartNew(() =>
{
Thread.Sleep(1000);
return 1;
}, cts.Token),
tf.StartNew(() =>
{
Thread.Sleep(1000);
return 2;
}, cts.Token),
};
// if at least one task will be faulted we exit all with cts.Cancel()
foreach (var task in childTasks)
{
task.ContinueWith(t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);
}
// process with results
tf.ContinueWhenAll(
childTasks,
(completedTasks) => completedTasks.Max(t => t.Result
)).ContinueWith((t) => Console.WriteLine(("Result is " + t.Result)), cts.Token);
});
parent.Start();
Thread.Sleep(5000);
}
}
Result is 2