title: Why can't I debug code in an async method?
body: <p>I actually started the night trying to learn more about MongoDB, but am getting hung up and the .NET await/async stuff. I am trying to implement the code shown on MongoDB's <a href="https://docs.mongodb.org/getting-started/csharp/query/" rel="noreferrer">site</a>. I've had to modify it a tad bit, so I could get my program to compile. I now have the following in my console application:</p>
  
  <pre><code>protected static IMongoClient _client;
  protected static IMongoDatabase _database;
  
  static void Main(string[] args)
  {
      _client = new MongoClient();
      _database = _client.GetDatabase("test");
  
      GetDataAsync();
  }
  
  private static async void GetDataAsync() //method added by me.
  {
      int x = await GetData();
  }
  
  private static async Task&lt;int&gt; GetData()
  {
      var collection = _database.GetCollection&lt;BsonDocument&gt;("restaurants");
      var filter = new BsonDocument();
      var count = 0;
      Func&lt;int&gt; task = () =&gt; count; //added by me.
      var result = new Task&lt;int&gt;(task); //added by me.
      using (var cursor = await collection.FindAsync(filter)) //Debugger immediately exits here, goes back to main() and then terminates. 
      {
          while (await cursor.MoveNextAsync())
          {
              var batch = cursor.Current;
              foreach (var document in batch)
              {
                  // process document
                  count++;
              }
          }
      }
  
      return count; //added by me
  }
  </code></pre>
  
  <p>When I run the application, the debugger will call into my <code>GetDataAsync()</code> method which in turn calls into the <code>GetData()</code> method. It gets to the line <code>using (var cursor = await collection.FindAsync(filter))</code> and then immediately returns to finish the <code>main()</code> method. </p>
  
  <p>Any break points I put below that line are ignored, as are any breakpoints I put in the <code>GetDataAsync()</code> method. Is this code just not getting run because the program exits? Can someone explain to me what is going on? </p>