Programing

SQLConnection을 폐기하기 전에 Close ()해야합니까?

crosscheck 2020. 8. 2. 17:25
반응형

SQLConnection을 폐기하기 전에 Close ()해야합니까?


Disposable objects에 대한 다른 질문에 따르면 using 블록이 끝나기 전에 Close ()를 호출해야합니까?

using (SqlConnection connection = new SqlConnection())
using (SqlCommand command = new SqlCommand())
{
    command.CommandText = "INSERT INTO YourMom (Amount) VALUES (1)";
    command.CommandType = System.Data.CommandType.Text;

    connection.Open();
    command.ExecuteNonQuery();

    // Is this call necessary?
    connection.Close();
}

using 블록이 있으므로 SQLCommand의 Dispose 메소드가 호출되고 연결이 닫힙니다.

// System.Data.SqlClient.SqlConnection.Dispose disassemble
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

.NET Reflector 를 사용하여 SqlConnection의 디스 어셈블 :

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }

    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

Dispose () 내부에서 Close ()를 호출합니다.


using 키워드는 연결을 올바르게 종료하므로 Close에 대한 추가 호출이 필요하지 않습니다.

SQL Server 연결 풀링 에 대한 MSDN 기사에서 :

"우리는 강력하게, 또는 당신은 연결 개체의 닫기 또는 폐기 방법 중 하나를 사용하여이 작업을 수행 할 수 있습니다 당신이 그렇게 연결이 풀에 반환됩니다를 사용하여 완료 당신은 항상 가까이에 해당 연결을. 추천 내부의 모든 연결을 열어 C #에서 명령문 사용 "

.NET Reflector를 사용한 SqlConnection.Dispose의 실제 구현은 다음과 같습니다.

// System.Data.SqlClient.SqlConnection.Dispose disassemble
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

Reflector를 사용하면 실제로 Dispose메서드 SqlConnection가 호출 하는 것을 볼 수 있습니다 Close().

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

아니요, SqlConnection에서 Dispose ()를 호출하면 Close ()도 호출됩니다.

MSDN-SqlConnection.Dispose ()


아니요, Using 블록을 사용하면 전화 Dispose()할 필요가 없으므로에 전화 할 필요가 없습니다 Close().


아니요, Dispose를 호출하기 전에 연결을 닫을 필요는 없습니다.

Some objects, (like SQLConnections) can be re-used afer calling Close, but not after calling Dispose. For other objects calling Close is the same as calling Dispose. (ManualResetEvent and Streams I think behave like this)


No, the SqlConnection class inherits from IDisposable, and when the end of using (for the connection object) is encountered, it automatically calls the Dispose on the SqlConnection class.

참고URL : https://stackoverflow.com/questions/1195829/do-i-have-to-close-a-sqlconnection-before-it-gets-disposed

반응형