析构函数中的紧密联系

chm*_*ifa 2 c# ado.net sqlconnection

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

我搜索了一下,发现是不可能的。

现在我尝试关闭它两次 - 并且它有效!

但我想知道这是否是一个好的解决方案。你怎么认为?

这是代码

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Rah*_*thi 5

连接是由Dispose方法关闭的,而不是由析构函数关闭的。

另请参阅MSDN 警告

警告

不要在类的 Finalize 方法中对 Connection、DataReader 或任何其他托管对象调用 Close 或 Dispose。在终结器中,您应该只释放您的类直接拥有的非托管资源。如果您的类不拥有任何非托管资源,请不要在类定义中包含 Finalize 方法。

处理连接的更好且推荐的方法是使用USING语句,这相当于说

try
{
  // your code
}
finally
{
  myobject.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

  • @chmouelkalifa 你为什么忘记首先处理掉?始终使用“using”语句。 (2认同)