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

VulpesRank #55 · 29.2K reputationPosted Mar 22, 2012, 11:29 AM EDT
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
Christopher Yellick10 reputationPosted Mar 22, 2012, 11:32 AM EDT
Sam HobbsRank #107 · 20.5K reputationPosted Mar 22, 2012, 4:16 PM EDT
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.
SenthilkumarRank #387 · 6.5K reputationPosted Mar 24, 2012, 8:50 PM EDT
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.