Should I dispose the IDisposable given to me?

Possible Duplicate:
Who should call Dispose on IDisposable objects when passed into another object?

Say you have a class with an interface like this:

public interface Foo
{
    Load(IDisposable something);
}

When implementing this method, should I call dispose when done? In other words, when a method of a class takes a Stream , Reader or anything else which is IDisposable , should this method dispose of the stream as well, or should this be left to whoever called the method?

I know either way would work, just curious what others more experienced would consider good conduct :-)


You should not call Dispose in Load method, because you might do more with IDisposable object. using should use outside to dispose if you don't need more. Sample code:

using (var something = new Something())
{
    IFoo foo = new Foo();
    foo.Load(something);

    // Do more with something
}

It depends on the documented behaviour of your interface.

If it makes sense for the stream to stay open for '(re)use' by the caller, then you might leave it open in some documented state (eg with the current position after such and such block).

Otherwise, the most helpful thing to do seems to be to dispose of it for the user.

Note that the CLR framework classes sometimes have specialized overloads to allow the caller to specify what should happen. See eg: http://msdn.microsoft.com/en-us/library/gg712952.aspx

public StreamReader(
    Stream stream,
    Encoding encoding,
    bool detectEncodingFromByteOrderMarks,
    int bufferSize,
    bool leaveOpen
)

我会添加一个参数,所以调用者可以告诉我是否处置它(我也为方法返回类型添加了void ):

public interface Foo 
{ 
    void Load(IDisposable something, bool disposeSomething); 
} 
链接地址: http://www.djcxy.com/p/54516.html

上一篇: 一个IDispose对象可以不具有可用的Dispose方法

下一篇: 我应该处置给我的IDisposable吗?