I needed a way to shave some additional time off of some reporting queries and opted to use async methods to perform some of the tasks in parallel. I'm pretty new to async so I made a test console application to prove the concept before plugging it into my asp.net MVC application. Everything works as expected in the console app but the same code never gets past "whenall" within asp.net. Here is my code:
//Synchronous call for outside world
public DataSet GetQueries_Sync()
{
Task<DataSet> Out = GetQueries();
Out.Wait();
return Out.Result;
}
//Run all needed tasks in parallel
private async Task<DataSet> GetQueries()
{
Task<DataTable> Task1 = QueryOne();
Task<DataTable> Task2 = QueryTwo();
Task<DataTable>[] Tasks = new Task<DataTable>[] { Task1, Task2 };
await Task.WhenAll(Tasks);
DataSet Out = new DataSet();
Out.Tables.Add(Task1.Result);
Out.Tables.Add(Task2.Result);
return Out;
}
//Individual Queries
private string ConnString = "MyConnectionString";
private Task<DataTable> QueryOne()
{
return Task.Run(() =>
{
DataTable Out = new DataTable();
string SQL = "";
SqlConnection Conn = new SqlConnection(ConnString);
SqlDataAdapter Adapter = new SqlDataAdapter(SQL, Conn);
Conn.Open();
Adapter.Fill(Out);
Out.TableName = "QueryOne";
Conn.Close();
return Out;
});
}
private Task<DataTable> QueryTwo()
{
return Task.Run(() =>
{
DataTable Out = new DataTable();
string SQL = "SQL Statement #2, ~30sec";
SqlConnection Conn = new SqlConnection(ConnString);
SqlDataAdapter Adapter = new SqlDataAdapter(SQL, Conn);
Conn.Open();
Adapter.Fill(Out);
Out.TableName = "QueryTwo";
Conn.Close();
return Out;
});
}
In asp.net (.net Framework 4.7), nothing past "Task.WhenAll(Tasks)" within GetQueries() is run even though each of the individual query functions return their results. The console app is basically the same except that the methods are static. Task.WhenAll(Tasks) continues as expected in the console environment. Any ideas why the same code would work within a console app but not within an asp.net app?