title: Task.ContinueWith Chain Sequence of Events
body: <p><strong>How do I get a <code>ContinueWith</code> to wait for two tasks to complete instead of just one?</strong></p>
  
  <p>I wanted to determine how I can chain a set of <code>Task</code>s together and have one run after the other having several levels of chaining.  I have three levels of chaining.  In the fist level I have a single task. I wanted the top level to finish before the second level starts.  In the second level I have 3 tasks.  I want 2 of the three tasks to complete before the third level starts. </p>
  
  <hr>
  
  <pre><code>TopLevel &gt; SecondLevel A \ ThirdLevel 
             SecondLevel B /
             SecondLevel C - Don't wait for this one for the third level
  </code></pre>
  
  <hr>
  
  <p>I have written the following sample program to test out how this would work as follows</p>
  
  <pre><code>class Program
  {
      private static Random rand = new Random();
      public static Random Rand { get { return rand; } }
      static void Main(string[] args)
      {
  
          Task topLevelTask = new Task(() =&gt; DoSomeWork("topLevelTask"));
          Task secondLevelTaskA = topLevelTask.ContinueWith((task) =&gt; DoSomeWork("secondLevelTaskA"), TaskContinuationOptions.AttachedToParent);
          Task secondLevelTaskB = topLevelTask.ContinueWith((task) =&gt; DoSomeWork("secondLevelTaskB"), TaskContinuationOptions.AttachedToParent);
          Task secondLevelTaskC = topLevelTask.ContinueWith((task) =&gt; DoSomeWork("secondLevelTaskC"), TaskContinuationOptions.AttachedToParent);
          Task thirdLevelTask = secondLevelTaskA.ContinueWith((task) =&gt; DoSomeWork("thirdLevelTask"), TaskContinuationOptions.AttachedToParent);
  
          topLevelTask.Start();
          Console.ReadLine();
      }
  
      private static void DoSomeWork(string task)
      {
          int sleep = Rand.Next(10000);
          Console.WriteLine("Thread {0}: Ticks {1}: Task {2}: Sleep: {3}", Thread.CurrentThread.ManagedThreadId, DateTime.Now, task, sleep);
          Thread.Sleep(sleep);
          Console.WriteLine("Complete Task {0}", task);
      }
  }
  </code></pre>
  
  <p>For the most part this does exactly what I want.  It starts the first task and waits for it to finish, starts the 3 second level tasks in parallel.  However, I can't figure out how to set up the third level to wait for both taskA and taskB since the <code>ContinueWith</code> is set with a single parent task.  </p>
  
  <p>I have attempted to put <code>ContinueWith</code> for the third level task on both taskA and taskB but then it runs twice.  Any help would be appreciated.  Here is the output of my sample program.</p>
  
  <p><img src="https://i.stack.imgur.com/cdh0d.png" alt="Program Output"></p>