Which of these is a better approach for performance? Note: For some operations I have up to five independent queries to execute.
var foo = await context.foos.ToListAsync();
var bar = await context.bars.ToListAsync();
vs.
var fooTask = context1.foos.ToListAsync();
var barTask = context2.bars.ToListAsync();
await Task.WhenAll(fooTask , barTask);
It would be great to use the same context without awaits, but this answer mentions that is not possible.
As you found out, the DbContext is not thread safe, therefore the only option to really run the queries in parallel would be to create a new DbContext for each Thread/Task.
The overhead of creating a new DbContext is pretty low. https://msdn.microsoft.com/en-us/library/cc853327.aspx
Since the object will come from different DbContexts and to further increase performance I recommend you also use NoTracking()
Edit:
I made a simple test program with a database I had:
The output is:
So yes, option 2 is faster...