创建IDisposable的类在C#中使用时,完成该清理的的SqlConnectionIDisposable、SqlConnection

2023-09-05 02:33:43 作者:心如苍井,空似水ヾ

在回答一个$p$pvious 有人质疑建议:

In an answer to a previous question somebody recommended:

拥有的SqlConnection类的成员变量,而且使课堂IDisposable接口和处分的SqlConnection的上课的时候​​被设置

have the SqlConnection a member variable of your class, but make the class IDisposable and dispose of the SqlConnection when the class is disposed

我已经把这个建议(下)的实现,但要检查这个实现是正确的(显然目前还不做任何事情,除了开放的连接,但想法是,将在那里这将方法使用的连接,这将是能够依靠其现有的和正在打开)。

I have put together an implementation of this suggestion (below) but wanted to check that this implementation is correct (obviously it doesn't currently do anything except open the connection but the idea is that there would be methods in there which would use the connection and which would be able to rely on it existing and being open).

public class DatabaseRecord : IDisposable
{
    protected SqlConnection connection;

    public DatabaseRecord()
    {
        connection = new SqlConnection("ConnectionString");
        connection.Open();
    }

    // IDisposable implementation

    private bool disposed;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }


    private void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                connection.Dispose();
            }
            disposed = true;
        }

    }

    // Destructor
    ~DatabaseRecord()
    {
        Dispose(false);
    }
}

将这项工作?将它们使用DatabaseRecord实例类需要做什么特别的事情或将处置自动被调用一次的情况下,不再使用/引用?这是更有效的/不是使用使用更好的(VAR连接=新的SqlConnection(...)){} 在需要连接的每个单独的方法体?

Will this work? Will classes which use instances of DatabaseRecord need to do anything special or will the Dispose automatically be called once the instances are no longer used/ referenced? Is this more efficient/ better than using using (var connection = new SqlConnection("...")) { } in each separate method body where the connection is needed?

推荐答案

SqlConnection的是有管理的资源,并应设置在如果(处置)块中。使用你的类的类应处理它,最好witrh一个使用块。无论这是不是单个使用块SqlConnections将取决于这个类的其他方法和如何使用它们。

SqlConnection is a managed resource, and should be disposed within the if (disposing) block. Classes using your class should dispose it, ideally witrh a using block. Whether this is better than individual using blocks for SqlConnections will depend on the other methods of this class and how they are used.