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?

Matt
  • 25,943
  • 66
  • 198
  • 303
  • have you got MARS on (I haven't actually tried this before but mars will probably make a difference)? – undefined Sep 18 '12 at 01:44
  • Forgive my ignorance, what is MARS – Matt Sep 18 '12 at 03:10
  • oh Google; Multiple Active Result Sets -- thanks! – Matt Sep 18 '12 at 03: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 http://stackoverflow.com/questions/6126616/is-dbcontext-thread-safe – undefined Sep 18 '12 at 03:17

1 Answers1

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.

Turbot
  • 5,095
  • 1
  • 22
  • 30
  • @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 – undefined Sep 18 '12 at 03:19
  • 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. – Turbot Sep 18 '12 at 13:45