Is it safe to use one Entity Framework Context per

2020-03-26 13:59发布

问题:

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.

回答1:

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.



回答2:

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.