dev guy

Adventures of a dev guy

Context Lifetimes -- Dispose or Reuse?

Context Lifetimes -- Dispose or Reuse?

  • Comments 11

Here's another topic which I believe is important to educate more folks on, but I just haven't had the time to carefully write something up.  As I was answering a question on the forum today, I realized that the answer might be good to share a bit more broadly, so here's a copy of that response.  The question which has come up several times is "When do I dispose of a context and recreate it vs when should I keep the existing context around and re-use it?"

If you are building a rich client application then you may well want to keep a context around for the life of the application, but you need to keep track of how many entities you have in that context.  It's all about understanding the overall pattern of your app.  There are some extremes and a whole spectrum of possibilities across the middle.

  • If your app's purpose is to efficiently add 200,000 entities to the database and then quit, then I would recommend doing batches rather than trying to cram all of them into the context at once and do one big save.  (This will clearly yield better performance.)
  • Similarly, if you are building a web service or app, then I would recommend spinning up a new context on every request in order to keep the server stateless.
  • At the other end of the spectrum you might have a rich client application that typically deals with a fairly small amount of data over its entire lifetime (think something like office communicator where you don't persist the discussions at all but you have a list of contacts and the typical size of that is small enough that if it all gets loaded into memory it wouldn't be that big a deal).  For this case I'd probably use one context for the life of the app and not worry about it.
  • In the middle somewhere come things like a rich client email or order entry app where there's some amount of data which is relatively constant in size and relatively small (the contacts you work with regularly, the products you usually sell or reference data like zipcode->state map or something) plus some amount of data that is transient (email messages arriving, being read and deleted, or orders entered and then sent off for processing).  In this kind of application I would use a single context and then keep careful track of what data is which kind.  For the "re-usable" data I would just leave it in the context, and for the transient data I would make sure that when I know it is no longer needed that I call Detach on it.  The detach method on the object context will remove items from the context without destroying it.  If you have a LARGE batch of items attached to a context, then the fastest thing generally is to destroy the context and recreate it (metadata caching will make this relatively fast), but if your context has some data you want to keep and some you want to detach, then you can call the detach method on everything you want to detach and continue using the context.

As one of my high-school math teachers used to say, clear as mud?

 - Danny

  • PingBack from

  • There is an interesting post over at

  • Comme pour LINQ To SQL, avec l'EF, la gestion du context n'est pas forcément aisée et divise les développeurs.

  • Isn't that just overly simplistic? There are a number of problems with keeping DataContexts around

    including the fact that you can't abort. You have to create a new one to abort changes. If one part of the app relies that the datacontext is sticky and another makes changes that require aborting and firing up a new one, how do you consolidate that? GUI apps are not exactly sequential and operations often occur out of order. If you have some operations that run 'concurrently' (not threaded but in the context of a business that might span several bunsiness objects) how do you consolidate the changes when only a few need to be updated and some thrown away?

    The real question is whether is it realistic on both ends of the spectrum to a) keep DataContext spun up all the time and possibly using large amoutns of memory and possible 'data inconsistencies' at the application level or b) keep spinning up new ones and eat CPU cycles in the process.

    I think the solution lies somewhere in the middle. Even Web apps that are build with Business Objects will need more than a single DataContext to deal with their own atomic state. Personally I prefer using a per business object DataContext - that way you have logical context with the ability to create additional instances if there's a conflict.

    I wrote about context management approaches a while back:

  • This is a frequently asked question on the forums, and Danny Simmons has now written a helpful blog post

  • In my ongoing series of trying to repurpose / further broadcast important topics that come up in the

  • In my ongoing series of trying to repurpose / further broadcast important topics that come up in the

  • One interesting question customers that are TDD practitioners usually ask is how to do unit testing with

  • One interesting question customers that are TDD practitioners usually ask is how to do unit testing with

  • Mike Taulty ponders best practices with the lifetime of a LINQ to SQL DataContext . For the Entity Framework

  • Here's a collection of  posts about the lifetime of these two related contexts. From Dinesh

Page 1 of 1 (11 items)
Leave a Comment
  • Please add 8 and 7 and type the answer here:
  • Post