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.
'developer tip' 카테고리의 다른 글
Express.js req.ip가 :: ffff : 127.0.0.1을 반환합니다. (0) | 2020.09.21 |
---|---|
Java로 현재 열려있는 창 / 프로세스 목록을 얻는 방법은 무엇입니까? (0) | 2020.09.21 |
UpperCase 문자의 Javascript 분할 문자열 (0) | 2020.09.21 |
Django에서 values () 항목의 이름을 바꾸는 방법은 무엇입니까? (0) | 2020.09.20 |
C # /. NET에서 로컬 컴퓨터의 FQDN을 찾는 방법은 무엇입니까? (0) | 2020.09.20 |