o-l*_*ogn 4 c# database performance database-connection linq-to-sql
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
这个查询好吗?或者数据库连接是否保持打开的时间超过必要的时间?
谢谢你的任何建议
连接将自动管理.但是,有一些(或至少可以像评论所示)与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;
}
Run Code Online (Sandbox Code Playgroud)
这里确保db.Dispose()在使用块退出时调用,从而明确地关闭连接.
编辑:在讨论之后,我自己查看了DataContext配置(也使用了Reflector)并找到了以下代码(FW 3.5),它来自DataContext.Dispose:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,有是资源得到释放:
DbConnection,日志(TextWriter)和DbTransaction.CommonDataServices.LoadOptions.提供者可能拥有需要处置(DbConnection和DbTransaction)的资源.此外,TextWriter可能必须处理日志,这取决于TextWriter用户分配给DataContext日志记录机制的实例,例如FileWriter然后自动关闭.
其他属性保持,据我所知 - 没有太多细节 - 只有内存,但这也可以通过dispose方法用于垃圾收集,但是,它确定何时内存实际被释放.
所以,最后我完全赞同casparOne的声明:
通常,共享像这样的数据访问资源是个坏主意.
您应该创建资源来访问数据库,执行操作,然后在完成后处置它们.