0

Can I do the following?

DbContext context = ...

var task1 = (
  from x in context.blah1 ...
  ...
  select x.alice
).ToListAsync();

var task2 = (
  from y in context.blah2 ...
  ...
  select y.bob
).ToListAsync();

task1.Start();
task2.Start();

// Some more stuff here

var result1 = await task1;
var result2 = await task2;

And have the two requests go off in parallel? Or is this very naughty? And if it is very naughty, why is it very naughty? And will this cause runtime exceptions or other nastiness?

I've read that contexts are not threadsafe, but there is only one thread here, as async/await doesn't spawn new threads, so I can't see how that's an issue.

Also are the .Start() calls necessary if I want the request to start running before // Some more stuff here? Or does .ToListAsync() kick off the execution itself?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Clinton
  • 22,361
  • 15
  • 67
  • 163
  • https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets But is that supported in ef? no idea. – Jeremy Lakeman Nov 25 '21 at 04:15
  • 1
    `Start()` is not necessary in this scenario. – Andy Nov 25 '21 at 04:54
  • Related: [Entity Framework Thread Safety](https://stackoverflow.com/questions/4455634/entity-framework-thread-safety), [Entity Framework and Multi threading](https://stackoverflow.com/questions/9099359/entity-framework-and-multi-threading). – Theodor Zoulias Nov 25 '21 at 05:01
  • You will need to use different context instances for it to work, see https://stackoverflow.com/questions/41749896/ef-6-how-to-correctly-perform-parallel-queries/41760048#41760048 – Peter Bons Nov 25 '21 at 07:13

1 Answers1

3

No, you cannot use one context in multiple threads as all of its internal collections to maintain state aren’t thread safe. They didn’t do it purposely as it would slow down the state management. Contexts are not supposed to live long and live on multiple threads. They should be short lived to do single unit of work.

Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • There isn't multiple threads in my question. There's no `Thread.Run`. – Clinton Nov 25 '21 at 06:37
  • @Clinton There is no visibile `Thread` in code due to the fact that a higher level threading api is used (namely async/await, Task). There are in fact multiple threads being used because once the I/O to the db is completed the continueing code can run of an different thread out of the pool – Peter Bons Nov 25 '21 at 07:15
  • Task.Start is multi threaded as task will run on different thread. It uses thread pool. Every asynchronous task can run on a different thread then calling thread that’s the whole point of async. – Akash Kava Nov 25 '21 at 07:16