Is there a way to handle each result on demand?
Similar to registering a delegation / callback that will be executed when the task completes
Yes, you just need to tweak your thinking a bit.
Forget registering callbacks ( ContinueWith is a dangerous, extremely low level API ). In addition, you almost never have to order tasks upon completion. Instead, think about your problem in terms of operations (tasks).
You now have a set of tasks that return a TimeSpan . Each item in this collection is the only operation that returns a TimeSpan . What you really want to do is the concept of a single higher-level operation that waits for the initial operation to complete and then executes your logic after the operation.
This is exactly what async / await for:
private static async Task<TimeSpan> HandleResultAsync(Task<TimeSpan> operation) { var result = await operation;
Now you want to apply this higher level operation to your existing operations. LINQ Select perfect for this:
IEnumerable<Task<TimeSpan>> tasks = ... IEnumerable<Task<TimeSpan>> higherLevelTasks = tasks.Select(HandleResultAsync); TimeSpan[] results = await Task.WhenAll(higherLevelTasks);
If you do not need a final collection of results, this can be further simplified:
private static async Task HandleResultAsync(Task<TimeSpan> operation) { var result = await operation;
source share