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?

4

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

There isn't multiple threads in my question. There's no Thread.Run.
@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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.