developer tip

SqlDataReader를 수동으로 닫고 폐기해야합니까?

optionbox 2020. 9. 21. 07:36
반응형

SqlDataReader를 수동으로 닫고 폐기해야합니까?


여기에서 레거시 코드로 작업하고 있으며 SqlDataReader닫히거나 처리되지 않는 인스턴스가 많이 있습니다. 연결이 끊어졌지만 리더를 수동으로 관리해야하는지 잘 모르겠습니다.

이로 인해 성능이 저하 될 수 있습니까?


다음과 같은 독자를 사용하지 마십시오.

SqlConnection connection = new SqlConnection("connection string");
SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection);
SqlDataReader reader = cmd.ExecuteReader();
connection.Open();
if (reader != null)
{
      while (reader.Read())
      {
              //do something
      }
}
reader.Close(); // <- too easy to forget
reader.Dispose(); // <- too easy to forget
connection.Close(); // <- too easy to forget

대신 using 문으로 래핑합니다.

using(SqlConnection connection = new SqlConnection("connection string"))
{

    connection.Open();

    using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader != null)
            {
                while (reader.Read())
                {
                    //do something
                }
            }
        } // reader closed and disposed up here

    } // command disposed here

} //connection closed and disposed here

using 문은 개체의 올바른 처리와 리소스 해제를 보장합니다.

잊어 버린 경우 청소를 가비지 수집기에 맡기고 시간이 걸릴 수 있습니다.


SqlCommand.ExecuteReader ()를 사용하여 인스턴스화 된 SqlDataReader를 삭제 해도 기본 연결이 닫히거나 삭제 되지 않습니다 .

There are two common patterns. In the first, the reader is opened and closed within the scope of the connection:

using(SqlConnection connection = ...)
{
    connection.Open();
    ...
    using(SqlCommand command = ...)
    {
        using(SqlDataReader reader = command.ExecuteReader())
        {
            ... do your stuff ...
        } // reader is closed/disposed here
    } // command is closed/disposed here
} // connection is closed/disposed here

Sometimes it's convenient to have a data access method open a connection and return a reader. In this case it's important that the returned reader is opened using CommandBehavior.CloseConnection, so that closing/disposing the reader will close the underlying connection. The pattern looks something like this:

public SqlDataReader ExecuteReader(string commandText)
{
    SqlConnection connection = new SqlConnection(...);
    try
    {
        connection.Open();
        using(SqlCommand command = new SqlCommand(commandText, connection))
        {
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }
    }
    catch
    {
        // Close connection before rethrowing
        connection.Close();
        throw;
    }
}

and the calling code just needs to dispose the reader thus:

using(SqlDataReader reader = ExecuteReader(...))
{
    ... do your stuff ...
} // reader and connection are closed here.

To be safe, wrap every SqlDataReader object in a using statement.


Just wrap your SQLDataReader with "using" statement. That should take care of most of your issues.

참고URL : https://stackoverflow.com/questions/744051/is-it-necessary-to-manually-close-and-dispose-of-sqldatareader

반응형