Reputation: 11895
My MVC4 app uses code-first Entity Framework 5.0. I want to access my SQL Server data from a timer thread. Is there any reason why I can't instantiate, use, and dispose an instance of the same derived DbContext class that I also use on the main ASP.NET worker thread? (Yes, I use the same using()
pattern to instantiate, use, and dispose the object on the main thread.)
A little problem context: My website has a WebsiteEnabled field in a table in the database. Currently, I incur a database fetch for each GET request to read that value. I want to change the code to read the value once every 15 seconds on a background thread, and store the value in a static variable that the GET request can read. I know that you run into problems if you try to instantiate multiple instances of the same DbContext on the same thread; I'm not sure if the same restrictions apply to instances of the same DbContext on different threads.
Upvotes: 1
Views: 2112
Reputation: 39807
We use a background thread as well to check for emails and do cleanups every so often in one of our larger MVC applications. As long as you create a new context (and dispose of it) on the background thread and not try and use the one from your main application thread, you will be fine. The DbContext
is not thread safe, meaning you cannot share it across multiple threads safely. This does not mean you cannot have multiple threads each with their own copy of the db context. The only caution is beware of concurrency issues (trying to update a row at the same time).
Upvotes: 1
Reputation: 11308
Statics and EF are recipe for a mess. Under asp.net, 1 app pool, many threads. Store statics if you must but not the context. So always make sure each thread gets its own context.
but given your problem, there is a simple out of the box solution I would use In thr controller that should have cached values. On the GET method You can cache per ID, for a specific period of time... Worth checking out. Let IIS, ASP.NET do work for you. :-)
[OutputCache(Duration = int.MaxValue, VaryByParam = "id", Location = OutputCacheLocation.ServerAndClient)]
public ActionResult Get(string id) {
// the value that can be cached is collected with a NEW CONTEXT !
Upvotes: 1