I have a sequence of tasks, where each one depends on the output of the previous one. I\'d like to represent this as a single Task object, whose result is the o
The easy way (using Microsoft.Bcl.Async):
static async Task AggregateAsync(
this IEnumerable items,
TState initial,
Func> makeTask)
{
var state = initial;
foreach (var item in items)
state = await makeTask(state, item);
return state;
}
The hard way:
static Task AggregateAsync(
this IEnumerable items,
TState initial,
Func> makeTask)
{
var tcs = new TaskCompletionSource();
tcs.SetResult(initial);
Task ret = tcs.Task;
foreach (var item in items)
{
var localItem = item;
ret = ret.ContinueWith(t => makeTask(t.Result, localItem)).Unwrap();
}
return ret;
}
Note that error handling is more awkward with the "hard" way; an exception from the first item will be wrapped in an AggregateException by each successive item. The "easy" way does not wrap exceptions like this.