简体   繁体   中英

What is the benefit of disposing of a LINQ to SQL DataContext?

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM