0

I have one context created and then using Parallel.ForEach(...) I perform multiple EF queries simultaneously.

I have been encountering 'The connection was not closed. The connection's current state is connecting.' and other exceptions along those lines.

I this due to the threaded nature of my application? Can you not use a single context simulataneously to simply read?

4
  • have you got MARS on (I haven't actually tried this before but mars will probably make a difference)? Commented Sep 18, 2012 at 1:44
  • Forgive my ignorance, what is MARS Commented Sep 18, 2012 at 3:10
  • oh Google; Multiple Active Result Sets -- thanks! Commented Sep 18, 2012 at 3:12
  • also by the looks of it @turbot is correct, dbcontext isnt threadsafe so you probably want to either pre-query all the data or run a separate context per thread, see stackoverflow.com/questions/6126616/is-dbcontext-thread-safe Commented Sep 18, 2012 at 3:17

1 Answer 1

3

Object context is not a thread safe, so you probably you don't want to use Parrallel.Foreach on multi threading scenarios

However, you can execute multiple queries on the same connection in parrallel with enabling MARS for example

foreach (var employee in context.employees.where(...))
{
   var department = employee.departments.FirstOrDefault(...);
}

however, you need to be aware of the performance.

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

2 Comments

@turbot my understanding is that dbcontext creation cost is very low, the only performance impact I can see is that queries will be smaller and more frequent
context creation is lightweight and cost of construction is low, however I don't have anything to compare with against the performance so I only wrote in general of be aware of performance measurement.

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.