加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 我的数据库连接是否已关闭? (Linq to Sql)

发布时间:2020-12-16 01:34:35 所属栏目:百科 来源:网络整理
导读:我正在使用 Linq to SQL并在博客文章中阅读有关尽快关闭数据库连接的信息.作为一个例子,他们展示了一个变量被转换为一个列表(使用.ToList())而不是实际返回Linq查询.我有以下代码: public static bool HasPassword(string userId) { ProjDataContext db = n
我正在使用 Linq to SQL并在博客文章中阅读有关尽快关闭数据库连接的信息.作为一个例子,他们展示了一个变量被转换为一个列表(使用.ToList())而不是实际返回Linq查询.我有以下代码:

public static bool HasPassword(string userId)
 {

    ProjDataContext db = new ProjDataContext();

    bool hasPassword = (from p in db.tblSpecUser
                                    where p.UserID == userId
                                    select p.HasPassword).FirstOrDefault();


    return hasPassword;
 }

这个查询好吗?或者数据库连接是否保持打开的时间超过必要的时间?

谢谢你的任何建议

解决方法

连接将自动管理.但是,有一些(或至少可以像评论所示)与DataContext相关的额外资源.在垃圾收集器销毁DataContext之前,不会释放这些资源.因此,通常最好确保在不再需要DataContext时调用dispose.

using (ProjDataContext db = new ProjDataContext()) {
    bool hasPassword = (from p in db.tblSpecUser
                                    where p.UserID == userId
                                    select p.HasPassword).FirstOrDefault();


    return hasPassword;
}

这里确保在using块退出时调用db.Dispose(),从而显式关闭连接.

编辑:在讨论之后,我自己查看了DataContext配置(也使用了Reflector)并找到了从DataContext.Dispose调用的以下代码(FW 3.5):

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        if (this.provider != null)
        {
            this.provider.Dispose();
            this.provider = null;
        }
        this.services = null;
        this.tables = null;
        this.loadOptions = null;
    }
}

所以有资源被释放:

>可能包含DbConnection,日志(TextWriter)和DbTransaction的提供程序.
> CommonDataServices.
>表字典.
> LoadOptions.

提供者可以保存需要处置的资源(DbConnection和DbTransaction).此外,可能必须处理日志的TextWriter,这取决于用户为DataContext的日志记录机制分配的TextWriter的实例,例如,然后自动关闭的FileWriter.

其他属性保持,据我所知 – 没有太多细节 – 只有内存,但这也可以通过dispose方法用于垃圾收集,但是,它确定何时内存实际被释放.

所以,最后我完全赞同casparOne的声明:

In general,sharing data-access resources like this is a bad idea.

You should create your resources to access the DB,perform your operations,and then dispose of them when done.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读