公共(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
, Dispose
从 Close
调用,
public override void Close()
{
Dispose(true);
}
Dispose
的实现也通过调用基础 Stream
的 Close
关闭流。
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/