Run sequence of tasks, one after the other

前端 未结 2 1653
醉梦人生
醉梦人生 2020-12-09 13:33

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

2条回答
  •  佛祖请我去吃肉
    2020-12-09 14:05

    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.

提交回复
热议问题