【问题标题】:Freeing connections and commands with using使用 using 释放连接和命令
【发布时间】:2019-02-20 17:53:39
【问题描述】:

当 SqlConnection 和 SqlCommand 都在单个 using 块中创建时,都在退出时被释放,还是需要嵌套 using 块?

using (SqlCommand command = new SqlConnection(ConnectionString).CreateCommand()) {

    // Use command..
}

【问题讨论】:

  • 是的,您需要在两者上都使用块。 using 块仅适用于该对象,而不适用于可能在其中创建的其他对象。您在这里所拥有的只会处理命令,连接会陷入困境。
  • 是的,您在连接、命令、任何事务、任何数据读取器等方面都需要using。但是:我强烈建议将所有这些丑陋的事情推迟到诸如Dapper 之类的工具,它非常更容易有效地使用 ADO.NET(而且它是免费的);例如,请参阅here

标签: c# sql-server ado.net


【解决方案1】:

using 块仅在块执行完成后在您声明的资源上调用 .Dispose()

MSDN: The Using Statement

所以,是的,您应该将SqlConnectionSqlCommand 都包含在using 语句中,以确保正确处置这两种资源。

编辑:您还可以像这样堆叠using 命令:

using (SqlConnection connection = new SqlConnection("connection string"))
    using (SqlCommand command = new SqlCommand("command", connection)) {
       // Your code here
}

【讨论】:

    【解决方案2】:

    最重要的部分是处置SqlConnection 对象,最好借助using 语句。所以按照你的例子,这将是这样做的适当方式:

    using (var cn = new SqlConnection(ConnectionString))
    {
        cn.Open();
    
        using (var command = cn.CreateCommand())
        {
            // Use command..
        }
    }
    

    这就是using 语句在幕后的意思,您可以了解它如何帮助减少样板代码:

    {
        var cn = new SqlConnection(ConnectionString);
    
        try
        {
            cn.Open();
    
            {
                var command = cn.CreateCommand();
    
                try
                {
                    // Use command..
                }
                finally
                {
                    command.Dispose();
                }
            }
        }
        finally
        {
            cn.Dispose();
        }
    }
    

    通过使用using 语句处理SqlConnection 实例,您可以确保在离开作用域后连接将被关闭,即使发生异常也是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多