title: Stung by using Linq deferred execution with async/await
body: <p>I am new to async/await and am tinkering with it to execute an operation on a list of objects using a list of tasks. I used Linq to generate both the list of objects and the list of tasks. The example below looks a little contrived, but it is a simplified version of my actual code.</p>
  
  <p>I found that when the code is executed as shown, after all tasks have completed (after the await), none of the object's Now properties have been updated, and all of the tasks still have a status of Running.</p>
  
  <p>I found that by eliminating Linq deferred execution by converting both objects and tasks to actual lists via .ToList&lt;>(), my code worked as expected (objects populated, tasks all run to completion).</p>
  
  <p>I am familiar with Linq deferred execution but I'm really confused by what is (isn't) going on in this code. I'm probably making a noob mistake with async/await...what is it?</p>
  
  <pre><code>private class Foo {
      public DateTime Now { get; set; }
  }
  
  private void Button_Click( object sender, EventArgs e ) {
      PopulateDates();
  }
  
  private async void PopulateDates() {
      var ordinals = new List&lt;int&gt;() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };
  
      var foos = ordinals.Select( o =&gt; new Foo() ); //.ToList();
  
      var tasks = foos.Select( f =&gt; PopulateDateAsync( f ) ); //.ToList();
  
      await Task.WhenAll( tasks );
  
      var firstNow = foos.ElementAt( 0 ).Now;
      var firstTaskStatus = tasks.ElementAt( 0 ).Status;
  }
  
  private Task PopulateDateAsync( Foo foo ) {
      return Task.Run( () =&gt; PopulateDate( foo ) );
  }
  
  private void PopulateDate( Foo foo ) {
      Thread.Sleep( 2000 );
      foo.Now = DateTime.Now;
  }
  </code></pre>