Monday, 17 October 2011

Should I Dispose of my LINQ DataContext?

Most developers construct a DataContext within a using statement to make sure that resources are cleaned up when leaving the block.

using( var dataContext = new LinqDataContext() )
{
   // Perform some data operations
   dataContext.Insert(obj)

} // Dispose of the DataContext and release resources

However it's not needed, the .Net garbage collector does that for you and the need to dispose of the DataContext is made less of critical requirement knowing that LINQ DataContexts do not keep expensive database connections open (something that surprised me) like some other ADO.Net objects.

To summarise, it isn't the end of the world and you aren't a bad developer if you don't dispose of your DataContext objects. I do however think it's good practice to work with IDisposable classes in this way; plus it releases those resources slightly quicker than just leaving it to the garbage collector.

No comments:

Post a Comment