Does closing a database connection in Dispose method is right?

后端 未结 2 1431
小鲜肉
小鲜肉 2020-12-17 03:52

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

相关标签:
2条回答
  • 2020-12-17 04:13

    conn.Dispose(); will also close the connection, so can't hurt changing it to follow the dispose pattern.

    But there functionally equivalent so there must be a problem else where.

    http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx

    If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is closed.

    0 讨论(0)
  • 2020-12-17 04:18

    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

    0 讨论(0)
提交回复
热议问题