在LINQ-SQL中,包装DataContext是using语句-优点缺点 [英] In LINQ-SQL, wrap the DataContext is an using statement - pros cons

查看:65
本文介绍了在LINQ-SQL中,包装DataContext是using语句-优点缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以就性能,内存使用量,编码的难易程度,正确的操作等因素在使用using语句包装DataContext与在LINQ-SQL中包装DataContext之间的优缺点提出自己的看法.

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.

更新:在一个特定的应用程序中,我体验到,没有将DataContext包装在using块中,由于没有为GC释放活动对象,因此内存使用量一直在增加.就像在下面的示例中一样,如果我持有对q个对象的列表和q个访问实体的引用,则会创建一个不为GC发布的对象图.

DataContext与使用

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

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(); 

谢谢.

推荐答案

相对于其他事情,创建DataContext可能会很昂贵.但是,如果您已完成此操作并希望尽快关闭连接,则可以这样做,同时也从上下文中释放所有缓存的结果.请记住,无论如何您都在创建它,在这种情况下,您只是让垃圾收集器知道有更多免费的东西可以摆脱.

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做成一个短期使用的对象,使用它,完成工作单元,离开……这正是您在使用中正在做的事情.

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.

所以优点:

  • 更快的封闭连接
  • 从处置中释放内存(内容中的缓存对象)

缺点-还有更多代码?但这不应该起到威慑作用,您在这里正确使用了using.

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

在此处查看Microsoft答案:

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

如果需要使用using/.Dispose()的简短版本:

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

简短答案;不,您不必这样做,但您应该 ...

这篇关于在LINQ-SQL中,包装DataContext是using语句-优点缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆