I thought it might be wiser to use Task.WaitAll
over multiple awaits. I looked into multiple awaits vs Task.WaitAll - equivalent? discussion and was confident that the latter would reap more benefits, but to my surprise, multiple awaits aren't doing a bad job either in terms of time consumed of all of them to complete sequentially. What could be the reason?
My code is as follows -
Stopwatch sw = Stopwatch.StartNew();
var t1 = Method1()
var t2 = Method2();
var t3 = Method3();
var t4 = Method4();
var t5 = Method5();
//note - in the real code there are like 10 await calls
//which I changed to use like above code.
Task.WaitAll(t1,t2,t3,t4,t5);
for (int i = 0; i < 20; i++)
{
someObject[i].prop1 = t1.Result[i];
someObject[i].prop2 = t2.Result[i];
someObject[i].prop3 = t3.Result[i];
someObject[i].prop4 = t4.Result[i];
someObject[i].prop5 = t5.Result[i];
}
sw.Stop();
Debug.WriteLine($"Time taken using wait all concept {sw.ElapsedMilliseconds}");
// Time taken using wait all concept 1346
// Time taken in **multiple** await is 995 ms
Update - 1 Below is the implementation of Method1(Methods2,3,4 and 5 are quite similar) hope it helps you help me.
private async Task<List<someObject>> Method1()
{
List<List<someObject>> something = new List<List<someObject>>();
var storedProcCriteria = new
{
//set up the object with parameters.
};
using (var db = _sqlConn.GetDbConnection())
{
string sql = @"someStoredProcedure";
SqlMapper.GridReader results = await db.QueryMultipleAsync(sql, storedProcCriteria, commandType: CommandType.StoredProcedure);
while (!results.IsConsumed)
{
data = results.Read<someObject>().ToList();
something.Add(data);
}
return something;
}
}
Update - 2 Actual comparison code
Stopwatch sw = Stopwatch.StartNew();
List<List<someObj1>> sth1 = await Method1()
List<List<someObj2>> sth2 = await Method1()
List<List<someObj3>> sth3 = await Method1()
List<List<someObj4>> sth4 = await Method1()
List<List<someObj5>> sth5 = await Method1()
for (int i = 0; i < claimData.Count; i++)
{
someObject[i].prop1 = sth1[i];
someObject[i].prop2 = sth2[i];
someObject[i].prop3 = sth3[i];
someObject[i].prop4 = sth4[i];
someObject[i].prop5 = sth5[i];
}
sw.Stop();
Debug.WriteLine($"Time taken in **multiple** await is {sw.ElapsedMilliseconds}");
// Time taken in **multiple** await is 995 ms