Is it possible to use one Entity Framework context for a stream? ... yes? as?

Perhaps these are two questions in one, I use one EF context for each request, but I want to use one for each thread, because I am going to do a difficult task in another thread during the request.

So is it safe? If so, how to do it? how to store objects in a stream and return them?

Thanks in advance.

+2
source share
2 answers

This is only safe if you have full control over the flow. This means that you must create a thread, and the thread should end after completion of work. If you use a thread pool to execute a request, you should not use a context for the thread. A thread pool is used, for example, for threads serving ASP.NET, ASP.NET MVC, or WCF requests. The context is not thread safe, so do not pass it among threads.

To save something in the stream, use the static variable and mark it with ThreadStaticAttribute .

+3
source

I would limit the scope of the EF context to a specific unit of work at the request level .

If you have units of work that have nothing to do with requests, you can create a new thread for this and use the new EF context, just get rid of it as soon as this part of the work is completed. Keep in mind that EF contexts are not thread safe, i.e. You cannot use the same context in more than one thread.

+1
source

Source: https://habr.com/ru/post/1411555/


All Articles