I have a database with three tables and I am making a program that will select and need to display results from all three at the same time.
In order to speed up the getting of records I decided to make the requests async so that they can happen at the same time.
Since you cannot perform more than one concurrent operation on the same DB context, I just instantiate three contexts, in total, and start a Linq query "ToListAsync()" on each one.
But something weird (for me) happens - the async version wasn't any faster than the sync version. Whether I get the results asynchroniously with ".ToListAsync()" or synchronously with ".ToList()" they take the same amount of time. With the sync version, the first operation takes ~2s to complete while the second ~170ms and the third ~90ms. I suppose some sort of execution plan or caching or establishing the connection is what makes the first request take a lot of time while the others complete almost instanteniously but I'd like to know WHY exactly this happens and if there is a way to make it faster.
Forgot to mention the async version takes the same amount of time - 2s.
Relevant code:
int maxRecords = 10;
var resultsTableOne = dbContext.tableOne.Where(log =>
log.DateUtc >= dateFrom || dateFrom == null)
&& (log.DateUtc <= dateTo || dateTo == null))
.OrderByDescending(log => log.Id).Take(maxRecords).ToList();
var resultsTableTwo = dbContext.tableTwo.Where(log =>
log.DateUtc >= dateFrom || dateFrom == null)
&& (log.DateUtc <= dateTo || dateTo == null))
.OrderByDescending(log => log.Id).Take(maxRecords).ToList();
var resultsTableThree = dbContext.tableThree.Where(log =>
log.DateUtc >= dateFrom || dateFrom == null)
&& (log.DateUtc <= dateTo || dateTo == null))
.OrderByDescending(log => log.Id).Take(maxRecords).ToList();
The select conditions are simplified here. For the async version, the "ToList" is replaced with "ToListAsync", which returns a task on which "GetAwaiter().GetResult()" is called after the code shown here (and the "dbContext" is replaced with three separate instances).
P.S.
The results for the sync version are the same with one and three DbContexts. I.e. it takes the same amount of time whether all three operations are performed on the same instance or each on its own instance.