Reputation: 6428
Basically I open a database connection when the application starts and it should remain open till the lifetime of the application.
I am using console application for this background job:
class Program
{
#region '----- Method(s) -----'
static void Main(string[] args)
{
}
~Program()
{
}
#endregion
}
Should I close database connection in my destructor or should I implement IDisposable?
Upvotes: 0
Views: 2595
Reputation: 812
You can have a implementation of dispose pattern here which is advisable. Otherwise, make sure you are inheriting your actual type from CriticalFinalizerObject
in order to enforce CLR to place your type instance in finalization queue irrespective of runtime conditions.
class Program:CriticalFinalizerObject
{
#region '----- Method(s) -----'
static void Main(string[] args)
{
}
~Program()
{
}
#endregion
}
Upvotes: 1
Reputation: 33978
Believe me, you dont want to do that, best practices say to use the connection only when needed and close it as soon as possible. If what you need is a transaction then you can use a Sql Transaction and put methods inside the using of sql Transaction
using(SqlConnection sqlconn= new ())
using(SqlTransaction sqltrann = new ())
{
{
method1
method 2
}
}
Upvotes: 2
Reputation: 6873
Hm..If you not creating an instance of program class then It need no finalizer because finalizers are called only for instance of objects. You need no nor Finalizer, nor IDisposable. You must to do so:
static void Main(string[] args)
{
db.Dispose();//In the end of console app executing code
}
Upvotes: 2
Reputation: 498904
Use IDisposable
.
The best way to do so is to instantiate it within a using
statement.
using (var conn = new SqlConnection(connectionString))
{
// your code here
}
Upvotes: 2