I'm trying to determine if it is acceptable to close the connection to a database in a class' destructor. My understanding is that I have no control over when the destructor is closed, but can I at least be certain that it will be closed by the time the program finishes executing. This is a small desktop application that connects to a local jet database. If it matters, I am using OleDb.
Loading
VulpesPosted Mar 22, 2012, 3:29 PM
This would ensure that the connection is closed immediately rather than waiting for the garbage collector to get around to calling the destructor.
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
SenthilkumarPosted Mar 25, 2012, 12:50 AM
There are many ways to close the database connection. It may be in finally block or destructor or using
But i suggest you to implement this in 'using' block.
using(SqlConnection sqlConnection = new SqlConnection(sqlConnStr))
{
}
The above using block will automatically handle the object release.
Sam HobbsPosted Mar 22, 2012, 8:16 PM
A good way to do that is to use Typed Datasets, and then .Net does it for you. A Typed Dataset would either be a TableAdapter or the Entity Framework. They will handle opening and losing connections automatically.
Christopher YellickPosted Mar 22, 2012, 3:32 PM