是否会在新的 SQL 连接上提供带有新 SQLConnection 调用的 SQLCommand Dispose?

Imb*_*234 2 c#

前言

我知道通常大多数 SQL 调用都是这样运行的

using(var cnn = new DbConnection("YOURCONNECTIONSTRINGHERE") 
{
  cnn.Open(); //Open the connection.
  using(var cmd = new DbCommand("YourSQL", cnn)
  {
    cmd.ExecuteScalar; //Or whatever type of execution you want.
  }
}
Run Code Online (Sandbox Code Playgroud)

这将正确处理连接和命令。

我的问题:这段代码会正确处理这两个对象吗?

  using(var cmd = new SqlCommand("YourSQL", new Connection("YOURCONNECTIONSTRINGHERE"))
  {
    cmd.ExecuteScalar; //Or whatever type of execution you want.
  }
Run Code Online (Sandbox Code Playgroud)

实际上,我正在使用一种提供并打开连接的方法。

public SqlConnection Connection()
{
    var product = new SQLConnection("ConnectionString");
    product.Open();
    return product;
}
Run Code Online (Sandbox Code Playgroud)

所以在一天结束时,电话看起来像这样:

  using(var cmd = new SqlCommand("YourSQL", Connection())
  {
    cmd.ExecuteScalar; //Or whatever type of execution you want.
  }
Run Code Online (Sandbox Code Playgroud)

我知道 SqlCommand 对象将被处理,但是在 using 参数声明中创建的 SQLConnection 会被处理吗?我试过运行一些简单的单元测试,但似乎没有定论。

Hoo*_*ini 5

这段代码会正确处理这两个对象吗?

using(var cmd = new SqlCommand("YourSQL", new Connection("YOURCONNECTIONSTRINGHERE"))
{
    cmd.ExecuteScalar; //Or whatever type of execution you want.   
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不会调用Dispose()上的连接。该using块确保cmd.Dispose()在块执行后立即调用,但连接保持打开状态。由于连接没有引用它的对象,它最终将被垃圾收集器关闭/处理。

如果您想立即处理命令连接,请尝试:

using (var con = Connection()) // <-- GetConnection() would be a better name
using (var cmd = new SqlCommand(con)
{
    cmd.ExecuteScalar; 
}
Run Code Online (Sandbox Code Playgroud)