我尝试在类的析构函数中关闭连接,以确保如果我忘记关闭它-它会自动关闭,并引发异常。
我搜索了一下,发现这是不可能的。
现在我试着关闭它两次-它工作了!!
但我想知道这是否是一个好的解决方案。你觉得呢?
代码
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();
}
}
连接是由Dispose
方法关闭的,而不是由析构函数关闭的。
另见MSDN注意事项
谨慎一个更好的、推荐的处理连接的方法是使用USING语句,这相当于说像不要在连接、数据读取器或任何对象上调用Close或Dispose类的Finalize方法中的其他托管对象。在一个结束器中,您应该只释放您的类所使用的非托管资源直接拥有。如果您的类不拥有任何非托管资源,请这样做不要在类定义中包含Finalize方法。
try
{
// your code
}
finally
{
myobject.Dispose();
}