title: Task.WaitAll not waiting for task to complete
body: <p>While trying to figure out the new (maybe not so new now, but new to me, anyway) <code>Task</code> asynchronous programming in C#, I ran into a problem that took me a bit to figure out, and I'm not sure why.</p>
  
  <p>I have fixed the problem, but I am still not sure why it was a problem to begin with. I just thought I'd share my experience in case anyone out there runs into the same situation.</p>
  
  <p>If any gurus would like to inform me of the cause of the problem, that'd be wonderful and much appreciated. I always like knowing just <em>why</em> something doesn't work!</p>
  
  <p>I made a test task, as follows:</p>
  
  <pre><code>Random rng = new Random((int)DateTime.UtcNow.Ticks);
  int delay = rng.Next(1500, 15000);
  Task&lt;Task&lt;object&gt;&gt; testTask = Task.Factory.StartNew&lt;Task&lt;object&gt;&gt;(
      async (obj) =&gt;
          {
              DateTime startTime = DateTime.Now;
              Console.WriteLine("{0} - Starting test task with delay of {1}ms.", DateTime.Now.ToString("h:mm:ss.ffff"), (int)obj);
              await Task.Delay((int)obj);
              Console.WriteLine("{0} - Test task finished after {1}ms.", DateTime.Now.ToString("h:mm:ss.ffff"), (DateTime.Now - startTime).TotalMilliseconds);
              return obj;
          },
          delay
      );
  Task&lt;Task&lt;object&gt;&gt;[] tasks = new Task&lt;Task&lt;object&gt;&gt;[] { testTask };
  
  Task.WaitAll(tasks);
  Console.WriteLine("{0} - Finished waiting.", DateTime.Now.ToString("h:mm:ss.ffff"));
  
  // make console stay open till user presses enter
  Console.ReadLine();
  </code></pre>
  
  <p>And then I ran the application to see what it spat out. Here is some sample output:</p>
  
  <blockquote>
    <p>6:06:15.5661 - Starting test task with delay of 3053ms.<br>
    6:06:15.5662 - Finished waiting.<br>
    6:06:18.5743 - Test task finished after 3063.235ms.</p>
  </blockquote>
  
  <p>As you can see, the <code>Task.WaitAll(tasks);</code> statement didn't do much. It waited a grand total of 1 millisecond before continuing execution.</p>
  
  <p>I have answered my own "question" below - but as I said above - if anyone more knowledgeable than I would care to explain why this doesn't work, please do!
  (I <em>think</em> it might have something to do with the execution 'stepping-out' of the method once it reaches an <code>await</code> operator - then stepping back in once the awaiting is done... But I am probably wrong) </p>