我尝试在类的析构函数中关闭连接,以确保如果我忘记关闭它 - 它会自动关闭,并引发异常。
我搜索了一下,发现了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();
}
}
最佳答案
连接由 Dispose
方法关闭,而不是由析构函数关闭。
另请参阅MSDN caution
Caution
Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition.
处理连接的更好且推荐的方法是使用 USING 语句,这相当于说
try
{
// your code
}
finally
{
myobject.Dispose();
}
关于c# - 析构函数中的紧密联系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32991700/