Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

c# - Does closing a database connection in Dispose method is right?

I've had a suspicion that a database connection used in one of our applications is not always closed. I went to see the code and I've found a class DataProvider that has SqlConnection object. The connection is opened in the constructor of this class and closed in it's Dispose method (don't judge that, I know keeping an open connection is evil, it's just not my code and it's not the point of the question anyway). The Dispose method is implemented like this:

protected virtual void Dispose(bool disposing)
{
    if (!_disposed)
    {
        if (disposing)
        {
            if (_conn != null)
                _conn.Close();
        }

        _disposed = true;
    }
}

The question is:
Does it always guarantee that the connection is closed?
Is this code right?

I think there should be _conn.Dispose() called - am I right and could it affect not closing the connection (probably not)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Dispose is never called automatically.

The connection will not be closed until the Dispose method of your object is explicitly called, or if your class in used in a using() block

A safer way is to call the dispose method in your finalizer and ensure the finalizer is suppressed when the Dispose method is called.

This article present the correct way to implement the pattern

Hope it helps !

Cédric


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...