Linq DataContext and Dispose

来源:互联网 发布:爱站seo 编辑:程序博客网 时间:2024/06/05 06:58

Linq DataContext and Dispose

A question many developers have with Linq and databases is this:

How important is it to call Dispose on a DataContext object?

Normally a quick web search gives an easy answer to common questions like this.  But sometimes Google fails us.  It turns out so many people have attempted to write about this with wrong or incomplete information that a web search returns mostly junk.

Here is a definitive answer, which I have finally learned after reading down to comment one hundred and twenty seven :) on a blog post by ScottGu, who runs the ASP.NET team at Microsoft.

Short answer:  It is generally not critical to call Dispose on Datacontext.

Longer answer: 
All objects in .NET are eventually disposed automatically by the automatic garbage collector.  The reason developers are paranoid about calling it explicitly is that if an object contains an expensive resource like an open database connection, then we can't afford to wait around for garbage collection, it would have a big impact on scalability.

The good news is that DataContext objects do not keep open database connections like some ADO.Net objects do, so it doesn't really hurt to let the garbage collector do it for you.

There is one caveat here though:  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.

Btw, a gigabyte of expensive ECC server memory is going for as little as 30 bucks now, so if your server is strained you can help it out pretty cheaply.

 

转载自:http://lee.hdgreetings.com/2008/06/linq-datacontex.html