I am trying to get a data set filled with multiple data tables asynchronously but it seems like taking the same execution time as its been before the asynchronous call. Can please someone give me some advise on by looking at the code snippet what I am doing wrong here.
In following code just assume that the result parameter has 4 items which are responsible of executing the stored procedure 4 times and return 4 data tables. The longest execution time for one particular stored procedure is around 7 seconds so I want all the data tables to be filled in no more than 7 seconds otherwise without asynchronous call the execution time go up to around 15 seconds which is not acceptable by any means.
var ds = await FillDataSetAsync(asyncConnectionString, result);
private Task<DataSet> FillDataSetAsync(string asyncConnectionString, List<Info> result)
{
var dataset = new DataSet();
return Task<DataSet>.Factory.StartNew(() =>
{
foreach (var item in result)
{
DataTable dt = new DataTable("");
using (SqlConnection conn = new SqlConnection(asyncConnectionString))
{
var functionQuery = "Execute_StoredProcedure";
SqlCommand comm = new SqlCommand(functionQuery, conn);
comm.Parameters.AddWithValue("Id", item.Id);
if (!string.IsNullOrWhiteSpace(item.Parameters))
{
comm.Parameters.AddWithValue("Parameters", item.OverrideParameters);
}
comm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt); dt.TableName = item.Id;
dataset.Tables.Add(dt);
}
}
return dataset;
});
}
Instead of
foreach (var item in result)
{
// your code
}
Try:
Parallel.ForEach(result, item =>
{
// your code
});