c# - 析构函数中的紧密联系

标签 c# ado.net sqlconnection

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

我搜索了一下,发现了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/

相关文章:

c# - 从登录页面将用户名保存在 session 中

c# - 将 Entity Framework 6 与 MySQL 结合使用

ms-access - 使用 C# OleDbConnection 的 Microsoft Access UPDATE 命令和命令不起作用

c# - 需要使用数据库表架构在 .net 中获取空数据表

SQL Server 2008R2 SSRS报告无法连接到数据源: Cannot create a connection to data source

sql-server - 保护连接字符串免受中间人的影响

c# - 将列表从 jQuery 传递到服务

c# - 在 2 个监视器上最大化 WPF 窗口

c# - 使用 Dapper QueryAsync 方法时 connection.OpenAsync 和 connection.Open 之间的区别

c# - 在 C# 中线程化 2 个 Web 服务调用和组合结果数据的最佳方法是什么?