Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LINQ-SQL, wrap the DataContext is an using statement - pros cons

Can someone pitch in their opinion about pros/cons between wrapping the DataContext in an using statement or not in LINQ-SQL in terms of factors as performance, memory usage, ease of coding, right thing to do etc.

Update: In one particular application, I experienced that, without wrapping the DataContext in using block, the amount of memory usage kept on increasing as the live objects were not released for GC. As in, in below example, if I hold the reference to List of q object and access entities of q, I create an object graph that is not released for GC.

DataContext with using

    using (DBDataContext db = new DBDataContext())
    {
        var q = 
            from x in db.Tables
            where x.Id == someId
            select x;

        return q.toList();
    }

DataContext without using and kept alive

  DBDataContext db = new DBDataContext()
  var q = 
        from x in db.Tables
        where x.Id == someId
        select x;

    return q.toList(); 

Thanks.

like image 259
hIpPy Avatar asked Feb 18 '10 21:02

hIpPy


2 Answers

A DataContext can be expensive to create, relative to other things. However if you're done with it and want connections closed ASAP, this will do that, releasing any cached results from the context as well. Remember you're creating it no matter what, in this case you're just letting the garbage collector know there's more free stuff to get rid of.

DataContext is made to be a short use object, use it, get the unit of work done, get out...that's precisely what you're doing with a using.

So the advantages:

  • Quicker closed connections
  • Free memory from the dispose (Cached objects in the content)

Downside - more code? But that shouldn't be a deterrent, you're using using properly here.

Look here at the Microsoft answer: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/2625b105-2cff-45ad-ba29-abdd763f74fe

Short version of if you need to use using/.Dispose():

The short answer; no, you don't have to, but you should...

like image 134
Nick Craver Avatar answered Oct 20 '22 12:10

Nick Craver


Well, It's an IDisposable, so I guess it's not a bad idea. The folks at MSFT have said that they made DataContexts as lightweight as possible so that you may create them with reckless abandon, so you're probably not gaining much though.....

like image 5
James Curran Avatar answered Oct 20 '22 14:10

James Curran