c# - 实例方法调用 Dispose

标签 c# design-patterns dispose idisposable

公共(public)方法在同一类中调用 IDisposable 的 Dispose 是否正确?

例如

public class Worker : IDisposable
{
    public void Close()
    {
       SendCloseCommand();
       Dispose();
    }

    public void Dispose()
    {
       ////other resources release
    }

    private void SendCloseCommand()
    {
    }
}

关于一次性模式的另一件事: 如果应该始终调用 Close,那么从 Dispose 方法调用还是更好?

如果没有,我应该把 Worker 类的用法放在到处的 try/catch/finally 中,以调用 Close。对吧?

正确的设计应该是?

public class Worker : IDisposable
{
    public void Close()
    {
       SendCloseCommand();
    }

    public void Dispose()
    {
       Close();
       ////other resources release
    }

    private void SendCloseCommand()
    {
        ////other stuff
    }
}

最佳答案

如果你看Microsoft implementation for StreamReader , DisposeClose 调用,

public override void Close()
{
    Dispose(true);
}

Dispose 的实现也通过调用基础 StreamClose 关闭流。

protected override void Dispose(bool disposing)
{
    // Dispose of our resources if this StreamReader is closable.
    // Note that Console.In should be left open.
    try {
        // Note that Stream.Close() can potentially throw here. So we need to 
        // ensure cleaning up internal resources, inside the finally block.  
        if (!LeaveOpen && disposing && (stream != null))
            stream.Close();
    }
    finally {
        if (!LeaveOpen && (stream != null)) {
            stream = null;
            encoding = null;
            decoder = null;
            byteBuffer = null;
            charBuffer = null;
            charPos = 0;
            charLen = 0;
            base.Dispose(disposing);
        }
    }
}

在您的类实现中,我将从您的 Close 方法中调用 Dispose,就像您在第一个代码片段中所做的那样。在 Dispose 中,我会检查 Worker 状态,如果它没有关闭则使用 SendCloseCommand 关闭它,然后释放资源。

public void Dispose()
{
   if(this.Status != Closed) // check if it is not already closed
     {
         SendCloseCommand();
     }

   ////other resources release
}

这将确保您的资源处置,即使您的类使用 using 语句,或者如果有人手动调用 Close

请记住在发出关闭命令之前检查您的 Worker 对象的状态。

关于c# - 实例方法调用 Dispose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25384256/

相关文章:

c# - 在 .NET 中重写 Dispose(bool disposing) 有什么意义?

c# - 如何按名称选择 TreeNode?

c# - 构建是否可以在一个平台上成功而在另一个平台上失败?

c# - 套接字缓冲它接收到的数据

c++ - 在 VisitorPattern 中结合访问者

java - 静态类/字段。你多久使用一次?

c# - 处理迭代器 block 的参数

c# - 是否可以强制将 "using"用于一次性类(class)?

C# RegEx.Split 分隔符后跟特定单词

design-patterns - 另一个针对特定问题的设计问题