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.
Basically I have the following:
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)
// Load content of one chart my.loadChartContent = function (data, callback) { $.post("/Dashboard/GetChartContent/", data, function (datain) { if (isFunction(callback)) callback(datain); }); };
A controller action which calls a database method in another class
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); }
The data class (_dataService) which fetches the data from the database with a SqlDataReader and loads a DataTable with that data.
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)
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?
Update: When I use SQLConnection.OpenAsync and ExecuteReaderAsync the code never finishes...and I don't get why?
public async Task<Query> 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;
}