gpt4 book ai didi

c# - 在析构函数中关闭连接

转载 作者:太空宇宙 更新时间:2023-11-03 21:17:35 24 4
gpt4 key购买 nike

我试图在我的类的析构函数中关闭一个连接,以确保如果我忘记关闭它 - 它会自动关闭,并引发异常。

我搜索了一下,然后创建了 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 语句,这相当于说 like

try
{
// your code
}
finally
{
myobject.Dispose();
}

关于c# - 在析构函数中关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32991700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com