title: Run sequence of tasks, one after the other
body: <p>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 <code>Task</code> object, whose result is the output of the end of the sequence. (If the tasks didn't depend on one another then I could do it in parallel and I would use <code>TaskFactory.ContinueWhenAll</code>.)</p>
  
  <p>I'd like to be able to implement this method:</p>
  
  <pre><code>static Task&lt;TState&gt; AggregateAsync&lt;T, TState&gt;(
      IEnumerable&lt;T&gt; items,
      TState initial,
      Func&lt;TState, T, Task&lt;TState&gt;&gt; makeTask);
  </code></pre>
  
  <p>How can I efficiently run the tasks one after another in sequence? I'm using C# 4.0 so I can't use <code>async</code>/<code>await</code> to do it for me.</p>
  
  <p><strong>Edit:</strong> I could write <code>AggregateAsync</code> like this:</p>
  
  <pre><code>static Task&lt;TState&gt; AggregateAsync&lt;T, TState&gt;(IEnumerable&lt;T&gt; items, TState initial, Func&lt;TState, T, Task&lt;TState&gt;&gt; makeTask)
  {
      var initialTask = Task.Factory.StartNew(() =&gt; initial);
      return items.Aggregate(
          initialTask,
          (prevTask, item) =&gt;
              {
                  prevTask.Wait(); // synchronous blocking here?
                  return makeTask(prevTask.Result, item);
              });
  }
  </code></pre>
  
  <p>But surely I'll get a batch of tasks, each of which blocks synchronously waiting for the one before it?</p>