我試圖在我的類的析構函數中關閉一個連接,以確保如果我忘記關閉它,它會自動關閉,並引發異常。析構函數中的關閉連接
我搜索了一下,我創建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();
}
}
他們總是告訴我不要在'destructor'使用'Dispose' – kevintjuh93
使用「使用」.........它會處理所有內容 – andy
僅僅實現'IDiposable'接口就足以去除資源。請參閱http://stackoverflow.com/questions/456213/destructor-vs-idisposable –