C#Linq-to-Sql-应该使用IDisposable处置DataContext [英] C# Linq-to-Sql - Should DataContext be disposed using IDisposable

查看:260
本文介绍了C#Linq-to-Sql-应该使用IDisposable处置DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几种处理数据库的方法,所有这些方法都通过调用

I have several methods that deal with DB and all of them start by calling

FaierDbDataContext db = new FaierDbDataContext();

由于Linq2Sql DataContext对象实现IDisposable,因此应将其与"using"一起使用吗?

Since the Linq2Sql DataContext object implements IDisposable, should this be used with "using"?

using (FaierDbDataContext db = new FaierDbDataContext()) {
    // use db here
}

以一种或另一种方式使用它的含义是什么?

What are the implications of using it one way or another?

推荐答案

与大多数实现的类型不同 IDisposable,DataContext不 真的需要处置-至少不需要 大多数情况下.我问马特·沃伦 关于这个设计决定,在这里 是他的回应:

Unlike most types which implement IDisposable, DataContext doesn't really need disposing - at least not in most cases. I asked Matt Warren about this design decision, and here was his response:

我们实施的原因有很多 IDisposable:

There are a few reasons we implemented IDisposable:

  • 如果应用逻辑除了在 预期将使用DataContext或 有效期您可以通过以下方式执行该合同 调用Dispose.延迟装载机 该实体仍将引用 DataContext并将尝试使用它 如果有任何代码尝试浏览 延迟属性.这些尝试 将失败.处置也迫使 DataContext转储其缓存 物化实体,使单个 缓存的实体不会意外 使所有实体都活着 通过该DataContext,这将 否则会导致看起来像是 内存泄漏.
  • 自动关闭DataContext连接的逻辑可以是 被骗离开连接 打开. DataContext依赖于 应用程序代码枚举全部 自进入以来的查询结果 结果集的结尾触发 连接关闭.如果 应用程序使用IEnumerable的 MoveNext方法而不是foreach C#或VB中的语句,可以退出 枚举过早.如果你的 应用程序遇到问题 连接没有关闭,你 怀疑自动关闭行为 无法正常工作,您可以使用Dispose 模式.
  • If application logic needs to hold onto an entity beyond when the DataContext is expected to be used or valid you can enforce that contract by calling Dispose. Deferred loaders in that entity will still be referencing the DataContext and will try to use it if any code attempts to navigate the deferred properties. These attempts will fail. Dispose also forces the DataContext to dump its cache of materialized entities so that a single cached entity will not accidentally keep alive all entities materialized through that DataContext, which would otherwise cause what appears to be a memory leak.
  • The logic that automatically closes the DataContext connection can be tricked into leaving the connection open. The DataContext relies on the application code enumerating all results of a query since getting to the end of a resultset triggers the connection to close. If the application uses IEnumerable's MoveNext method instead of a foreach statement in C# or VB, you can exit the enumeration prematurely. If your application experiences problems with connections not closing and you suspect the automatic closing behavior is not working you can use the Dispose pattern as a work around.

来自来源

这篇关于C#Linq-to-Sql-应该使用IDisposable处置DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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