当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - Is it safe to use one Entity Framework Context per thread? ... yes? how?

问题描述:

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.

网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: