views:

68

answers:

2

What is the benefit of disposing of a LINQ to SQL DataContext? Or, is there a problem with not disposing of these DataContext objects?

For instance, for easy coding, I might want to do something like...

var list = from p in (new MyDataContext()).People where p.LastName.Contains("sommar") select p;

In this case, I have new'd up an instance but not "closed" it or disposed of it in any way. Is it still out there floating around with potential to cause me problems? To up the ante, let's put that in a loop where it gets called 2000 times. <italian:accent>You got a problem with that?</italian:accent>

A: 

L2S data contexts don't need to be closed or disposed. However, I don't think I would want to do what you are doing, newing up a new one 2000 times in a loop. A data context is a heavy weight object, much like a SQLConnection on major steroids. I wouldn't want the overhead of creating 2000 in a loop. OTOH, you don't want them living for too long either.

New one up, do your unit of work and then let the framework dispose of it, or do it yourself. There is no harm in doing so.

Randy Minder
Point taken. It was a hypothetical situation of course. So, what you're saying is, the only problem with newing up 2000 data contexts would be poor performance while the loop is running. No memory leaks or anything like that?
Byron Sommardahl
-1 for "heavy weight object", +1 for "do your unit of work". The DataContext is made and designed to be used for a unit of work at a time. Calling it a heavy weight object might prompt people to keep it alive for longer than a single unit of work, leading to significantly more problems. While creating 2000 in a tight loop might be excessive, it might not be appropriate to do all iterations under a single data context either-- especially if simultaneous asynchronous access is occurring via another DataContext.
Greg D
@Byron - Cannot comment on whether there are memory leaks with Context objects. But I would not new up 2000 in a loop unless you are forced to for technical reasons.
Randy Minder
+1  A: 

Check out this which also contains a link to this.

thedugas