Linq to Sql 是否自动关闭连接?

Does Linq to Sql close connections automatically?

Linq to Sql 是否自动关闭连接?或者我应该使用 using?

var db = new DataContext();
// Codes

using (var db = new DataContext())
{
    // Codes
}

using 版本是您能做的最好的。底层连接没有关闭,这是一件好事。连接保存在一个池中,以便它们可以被回收。

不要混淆您的代码 关闭 与实际底层物理连接的连接。

您必须关闭连接,处理此问题的最佳方法(最佳实践)是 using 语句。

当你使用 using 语句时,连接将被管理 automatically.The DataContext class 实现了 IDisposable 接口,所以你需要什么to 是在您完成 DataContext 实现时调用 Dispose。

来自C# In Depth

There are a few reasons we implemented IDisposable:

  • 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.