title: How to make this asynchronous? (async, await - C#, MVC)
body: <p>I just tried to make a part of my ASP .NET MVC Application asynchronous but even after reading and trying out a lot I don't really understand the async-await pattern and hope someone could give me a hint.</p>
  
  <p>Basically I have the following:</p>
  
  <ol>
  <li><p>A javascript call to my controller which fetches a partial View for a chart (this happens several times after page load for a lot of charts)</p>
  
  <pre><code>// Load content of one chart
  my.loadChartContent = function (data, callback) {
  $.post("/Dashboard/GetChartContent/", data, function (datain) {
      if (isFunction(callback))
          callback(datain);
  });
  };
  </code></pre></li>
  <li><p>A controller action which calls a database method in another class</p>
  
  <pre><code>public ActionResult GetChartContent(int id, bool isDraft = false)
  {
      //do something
      //...
  
      var chartdata = _dataService.GetDataForChart(chart, isDraft, _user.Id); //long running query
  
      //do something with chartdata
  
      return View(chartdata);
  }
  </code></pre></li>
  <li><p>The data class (_dataService) which fetches the data from the database with a SqlDataReader and loads a DataTable with that data.</p></li>
  </ol>
  
  <p>The problem is that although the javascript is executed asynchronously the Controller-Actions seems to be blocked until a result from the DataService class returns. I would like to start all queries to the database and wait for the results asynchronously, so that long-running queries don't block shorter ones. (In SQL Server Profiler I see the queries as Begin-End, Begin-End, Begin-End => but it should be begin-begin-begin - end-end-end)</p>
  
  <p>Where should I use async-await? Is it enough to use it (somehow) for my controller action or is it necessary to make the whole "call-chain" asynchronous?</p>
  
  <p><strong>Update:</strong>
  When I use SQLConnection.OpenAsync and ExecuteReaderAsync the code never finishes...and I don't get why?</p>
  
  <pre><code>    public async Task&lt;Query&gt; GetSqlServerData(Query query)
      {
          var dt = new DataTable();
          var con = new SqlConnection(query.ConnectionString);
  
          await con.OpenAsync();
          var cmd = new SqlCommand(query.SelectStatement, con);
          var datareader = await cmd.ExecuteReaderAsync();
  
          dt.Load(datareader);
  
          con.Close();
          query.Result = dt;
          return query;
      }
  </code></pre>