我试图在我的类的析构函数中关闭一个连接,以确保如果我忘记关闭它,它会自动关闭,并引发异常。析构函数中的关闭连接
我搜索了一下,我创建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 –