2015-10-07 57 views
1

我试图在我的类的析构函数中关闭一个连接,以确保如果我忘记关闭它,它会自动关闭,并引发异常。析构函数中的关闭连接

我搜索了一下,我创建here它不能做到。

现在我试着关闭它两次 - 它的工作原理!

但我想知道如果这是一个很好的解决方案。 你觉得呢?

这里是代码

public class MyCommand : IDisposable 
{ 
    public readonly DbCommand command; 
    public MyCommand(string ConnectionString, DbProviderFactory factory) 
    { 
     var tempConnexion = factory.CreateConnection(); 
     tempConnexion.ConnectionString = ConnectionString; 
     tempConnexion.Open(); 
     var t = tempConnexion.BeginTransaction(IsolationLevel.ReadCommitted); 
     command = tempConnexion.CreateCommand(); 
     command.Connection = tempConnexion; 
     command.Transaction = t; 
    } 
    public MyCommand(string ConnectionString, DbProviderFactory factory, string requete) 
     : this(ConnectionString, factory) 
    { 
     command.CommandText = requete; 
    } 
    public MyCommand(string ConnectionString, string provider) 
     : this(ConnectionString, DbProviderFactories.GetFactory(provider)) { } 
    public MyCommand(string ConnectionString, string provider, string requete) 
     : this(ConnectionString, DbProviderFactories.GetFactory(provider), requete) { } 

    public static implicit operator DbCommand(myCommand c) 
    { 
     return c.command; 
    } 
    public void Dispose() 
    { 
     try 
     { 
      var t = command.Transaction; 
      if (t != null) 
      { 

       t.Commit(); 
       t.Dispose(); 
      } 
     } 
     catch { } 
     try 
     { 
      if (command.Connection != null) 
       command.Connection.Dispose(); 
      command.Dispose(); 
     } 
     catch { } 
    } 
    ~MyCommand() 
    { 
     if (command != null && command.Connection != null && command.Connection.State == ConnectionState.Open) 
      for (int i = 0; i < 2; i++)//twice to get the handle - it's working! 
       Dispose(); 
    } 
} 
+0

他们总是告诉我不要在'destructor'使用'Dispose' – kevintjuh93

+1

使用“使用”.........它会处理所有内容 – andy

+0

仅仅实现'IDiposable'接口就足以去除资源。请参阅http://stackoverflow.com/questions/456213/destructor-vs-idisposable –

回答

3

的连接是通过所述Dispose方法由析构关闭不。

另见MSDN caution

注意

不要调用关闭或Dispose一个连接,一个DataReader或在您的类的Finalize方法的任何其他 管理对象。在 终结器中,您应该只发布您的类 直接拥有的非托管资源。如果您的班级没有任何非托管资源,则 的班级定义中不包含Finalize方法。

一个更好更应对连接推荐的方法是使用使用声明,等于说像

try 
{ 
    // your code 
} 
finally 
{ 
    myobject.Dispose(); 
} 
+0

是的。但是如果我忘记处理 - 析构函数会处置它。 –

+2

@chmouelkalifa为什么你忘记放在第一位?总是使用'using'语句。 –

+0

谨慎 - 我知道,我指的是它。但无论如何,我只需要处理它两次。为什么不这样做? –