简体   繁体   English

我应该在控制台应用程序中使用析构函数还是IDisposable

[英]Should I use destructor or IDisposable in Console application

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? 我应该在析构函数中关闭数据库连接还是应该实现IDisposable?

Use IDisposable . 使用IDisposable

The best way to do so is to instantiate it within a using statement . 最好的方法是在using语句中实例化它。

using (var conn = new SqlConnection(connectionString)) 
{
    // your code here
}

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. 您既不需要Finalizer,也不需要IDisposable。 You must to do so: 您必须这样做:

static void Main(string[] args)
{
    db.Dispose();//In the end of console app executing code
}

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 如果您需要的是事务,则可以使用Sql事务并将方法放在sql事务的使用中

using(SqlConnection sqlconn= new ())
   using(SqlTransaction sqltrann = new ())
{
  {    
     method1
     method 2
  }
}

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. 否则,请确保要从CriticalFinalizerObject继承您的实际类型,以强制CLR将您的类型实例放置在终结队列中,而与运行时条件无关。

class Program:CriticalFinalizerObject
 {
        #region '----- Method(s) -----'
        static void Main(string[] args)
        {

        }

        ~Program()
        {

        }
        #endregion
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM