Dispose your DataContext After use

This is my first blog post on here, so Hello from me. 

Rather than just have a meaningless 'hello' first post, i thought i would at least post something useful (albeit rather small)..

With all the talk of LINQ at the moment there are a lot of examples popping up on sites and most of them follow this kind of format...

myDbDataContext ctx = new myDbDataContext("connectionString");

var query
= from.... //great LINQ example etc...


//oh, wait, no disposal of my data context?

When i first started learning LINQ I was pretty curious as to why most examples do not offer some kind of indication that disposal is required.  Maybe because that is exactly what they are - examples.  Regardless, i have always disposed my dataContext objects, usually taken care of automatically by wrapping them in a using block.

It is advised on various sites, as pointed out in this MSDN forum post

I am currently preparing a rather long post on SEO management for Asp.Net and hope to have that up soon.

 Subscribe in a reader

3 Comments

  • I just wanted to point out that it is not critical to call Dispose on a DataContext object.

    Since it has been difficult for me to find a complete explanation of this I wanted to share this fact.

    For a more complete explanation of why this is true, please see:
    http://lee.hdgreetings.com/2008/06/linq-datacontex.html

    Regards,
    LTG

  • Fair point - but towards the end of your article you state that...

    "the DataContext does track change states for the data, and by disposing it you would release this memory more quickly.  In almost all apps this difference wont be significant.  However if you have a web site that is using all memory available this is one of many optimizations you could make."

    why bother going back to make such optimizations when you can do them in the first place?

    i have been in the situation where i have had to go back and clean up/optimze a previous developers mess and it can be a time consuming and frustrating task!

  • Here's Stephen Walther's take on the matter:

    http://weblogs.asp.net/stephenwalther/archive/2008/08/19/asp-net-mvc-tip-34-dispose-of-your-datacontext-or-don-t.aspx

Comments have been disabled for this content.