title: unexpected async await behavior in mstest unit test
body: <p>I'm having newbie problems testing an async method. I've read a few other posts, including <a href="https://stackoverflow.com/questions/12625595/how-to-correct-write-test-with-async-methods?rq=1">How to correct write test with async methods?</a>, and I <em>think</em> I'm doing things correctly, but I'm clearly missing something.</p>
  
  <p>Here's the code I'm trying to test:</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Temporary method used to simulate the time required to generate a report.
  /// &lt;/summary&gt;
  public virtual async Task GenerateTestReportAsync()
  {
      ++ActiveTaskCounter;
  
      await Task.Delay(2000);
  
      --ActiveTaskCounter;
  }
  </code></pre>
  
  <p>And here's the test (yes, I could/should improve it by storing the ActiveTaskCounter values in a list, but that's beside the point):</p>
  
  <pre><code>[TestMethod]
  public async Task GenerateTestReportAsyncUpdatesActiveTaskCounter()
  
      var bayViewModel = CreateBayViewModel();
  
      var invocationCount = 0;
      bayViewModel.PropertyChanged += (sender, args) =&gt;
          {
              if (args.PropertyName == "ActiveTaskCounter")
              {
                  ++invocationCount;
              }
          };
  
      await bayViewModel.GenerateTestReportAsync();
  
      //Thread.Sleep(2100); // TODO: Why is this needed?
      Assert.AreEqual(2, invocationCount);
      Assert.AreEqual(0, bayViewModel.ActiveTaskCounter);
  }
  </code></pre>
  
  <p>The test always passes with the Thread.Sleep uncommented. It always fails with the Thread.Sleep commented, as shown above. Why is this? I assumed the code below the "await bayViewModel.GenerateTestReportAsync()" wouldn't even execute until GenerateTestReportAsync was <em>really</em> finished.</p>
  
  <p>BTW, I'm using:
  Microsoft Visual Studio Ultimate 2012
  Version 11.0.51106.01 Update 1
  Microsoft .NET Framework
  Version 4.5.50709</p>
  
  <p>Thanks for any help you can provide! This has me stumped :-|</p>
  
  <p>EDIT: Here's a minimal repro of the view model class...</p>
  
  <pre><code>using System.ComponentModel;
  using System.Threading.Tasks;
  
  public class BayViewModel : INotifyPropertyChanged
  {
      public BayViewModel()
      {
          PropertyChanged = (sender, args) =&gt; { };
      }
  
      public event PropertyChangedEventHandler PropertyChanged;
  
      private int _activeTaskCounter;
      public int ActiveTaskCounter
      {
          get
          {
              return _activeTaskCounter;
          }
          set
          {
              _activeTaskCounter = value;
              PropertyChanged(this, new PropertyChangedEventArgs("ActiveTaskCounter"));
          }
      }
  
      public virtual async Task GenerateTestReportAsync()
      {
          ++ActiveTaskCounter;
  
          await Task.Delay(2000);
  
          --ActiveTaskCounter;
      }
  }
  </code></pre>