Rod
Rod

Reputation: 4451

Should I dispose of an EF context more frequently?

I'm working on my first application that will use entity framework. I've got a simple WPF app, which is page based. I have a EF context defined at the class level in the page, and I instantiate it in the page's load event. Then basically I just leave it there, using it as the user makes various choices, etc. However, many years experience in programming makes me think that I shouldn't just leave this context open. Should I new it up each time I need to use it for something, or doesn't it matter?

I'm working with VS 2010, .NET 4.0.

Upvotes: 2

Views: 93

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

EF Contexts are designed to be short lived. They don't do a lot of housekeeping, and tend to allocate memory without concern for freeing it in the short term. In addition, change tracking continues over time and is cumulative, so the longer the context exists the more memory for change tracking it allocates.

Rule of thumb, use the smallest scope necessary, and keep the context around the shortest amount of time it makes sense to.

Upvotes: 5

Related Questions