I tried to make an async database call to SQL Server and use it along with new ASP.NET MVC 4 async features but it strangely does not return at all. I debugged the code, works nicely but somehow the HTTP request hangs open forever.
Here is what I did:
This is the database call method:
public async Task<IEnumerable<Car>> GetCarsAsync() {
var connectionString = ConfigurationManager.ConnectionStrings["CarGalleryConnStr"].ConnectionString;
var asyncConnectionString = new SqlConnectionStringBuilder(connectionString) {
AsynchronousProcessing = true
}.ToString();
using (var conn = new SqlConnection(asyncConnectionString)) {
using (var cmd = new SqlCommand()) {
cmd.Connection = conn;
cmd.CommandText = selectStatement;
cmd.CommandType = CommandType.Text;
conn.Open();
using (var reader = await cmd.ExecuteReaderAsync()) {
return reader.Select(r => carBuilder(r)).ToList();
}
}
}
}
Here, Select method on SqlDataReader is an extension method which I implemented. carBuilder private method just returns back an instance of Car class.
This is the controller class:
public class HomeController : Controller {
private readonly GalleryContext ctx = new GalleryContext();
public async Task<ViewResult> IndexAsync() {
return View("Index", await ctx.GetCarsAsync());
}
}
Any idea what I am missing?