2015-10-07 42 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

謹慎 - 我知道,我指的是它。但無論如何,我只需要處理它兩次。爲什麼不這樣做? –