2

Probably these are two questions in one, I am using one EF context per request, but I want to use one per thread, because I am going to make some complex task in another thread during the request.

So, is it safe? If the answer is yes, how to do it? how to store objects in thread and get them back?

Thank you in advance.

k-dev
  • 1,627
  • 19
  • 30

2 Answers2

3

It is safe only if you have full control over the thread. It means you must create the thread and thread must die after finishing the job. If you use thread pool to query work you mustn't use context per thread. Thread pool is used for example for threads serving ASP.NET, ASP.NET MVC or WCF requests. Context is not thread safe so do not share it among threads.

To store something per thread use static variable and mark it with ThreadStaticAttribute.

Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
1

I would limit the scope of the EF context to a particular unit of work on a request level.

If you have units of work that are unrelated to requests by all means you can spawn a new thread for that and use a new EF context, just dispose of it once that unit of work has completed. Be aware though that EF contexts are not thread safe, i.e. you cannot use the same context in more than one thread.

BrokenGlass
  • 149,257
  • 27
  • 271
  • 318
  • See comments here too ... http://stackoverflow.com/questions/5414076/ef4-objectcontext-lifetime/5414475#5414475 – JTew Mar 30 '11 at 22:57