在ExecuteReader()中使用CommandBehavior.CloseConnection的用途/优点是什么

Vij*_*dra 16 c# ado.net

任何人都可以告诉我CommandBehavior.CloseConnection传递这个作为参数的用途和好处是com.ExecuteReader(CommandBehavior.CloseConnection)什么?

Jef*_*nal 19

在读取数据读取器时需要打开连接,并且希望尽快关闭连接.通过指定CommandBehavior.CloseConnection何时调用ExecuteReader,可确保代码在关闭数据读取器时关闭连接.

但是你应该已经立即处理你的连接(而不仅仅是关闭它们),在这种情况下,这样做最多只能获得边际(几乎肯定无法测量)的好处.

例如,此代码立即关闭其连接(执行处理它所需的任何其他工作),而不指定命令行为:

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(commandText, connection))
{
    connection.Open();
    using (SqlDataReader reader = command.ExecuteReader()) 
    {
        while (reader.Read())
           // Do something with the rows
    }
}
Run Code Online (Sandbox Code Playgroud)

  • "使用"获胜! (6认同)
  • 不,处置已经关闭的连接是100%正常. (4认同)
  • “但你应该已经立即处理你的连接”。有时这样做并不方便。例如,您希望将“reader”返回给调用者并让它处理数据。那么连接必须超出调用函数的范围。 (2认同)

Bru*_*nez 6

用于CommandBehavior.CloseConnection创建连接但返回a的函数IDataReader.要非常小心Dispose()IDbConnection例外只有在创建读者面前:

IDataReader ReadAll()
{
    var connection = new SqlConnection(connectionString);
    try
    {
        connection.Open();
        var command = connection.CreateCommand();
        command.CommandText = "SELECT * FROM mytable";
        var result = command.ExecuteReader(CommandBehavior.CloseConnection);
        connection = null; // Don't dispose the connection.
        return result;
    }
    finally
    {
        if (connection != null)
            connection.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)