繁体   English   中英

实例方法调用Dispose

[英]Instance method call Dispose

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

例如

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

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

    private void SendCloseCommand()
    {
    }
}

关于一次性模式的另一个问题:如果应该总是调用Close,那么从Dispose方法调用是否更好?

如果不是这样,我应该把工人类的用法在一个try / catch /终于无处不在,调用Close。 对?

应该是正确的设计吗?

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

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

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

如果您查看StreamReader Microsoft实现 ,则从Close调用Dispose

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

并且Dispose的实现也通过调用Close of base Stream Close Stream

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语句一起using ,或者任何人手动调用Close

在发出Close Command之前,请记住检查Worker对象的状态。

Microsoft有一些关于在实现IDisposable的类上使用Close方法的建议。 它是Dispose Pattern指南的一部分:

除了Dispose()之外, CONSIDER提供方法Close() ,如果close是该区域中的标准术语。

这样做时,将Close实现与Dispose相同并考虑显式实现IDisposable.Dispose方法非常重要。

public class Stream : IDisposable {
    IDisposable.Dispose(){
        Close();
    }
    public void Close(){
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

因此,微软的建议是隐藏Dispose并让它调用Close来进行实际的清理。 另外,请记住有关Dispose多次调用的指南:

DO允许多次调用Dispose(bool)方法。 第一次调用后,该方法可能选择不执行任何操作。

遵循这些指导原则可使您的代码与.NET库保持一致,并且您将避免混淆是否应关闭或处理您的类以进行适当的清理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM