简体   繁体   中英

Do I need to dispose transient disposable objects?

I have a class that creates several IDisposable objects, all of these objects are then passed to another 'manager' class in a 3rd party library. As I need some of the objects in later calls I kept a local field reference to the created objects so that I could access them at a later time. When I ran FxCop on the class it said that I should implement IDisposable, due to the disposable objects that I kept a reference to. My questions are:

  1. Should I implement IDisposable for my class? (or is it the manager's responsibility?)
  2. If so, should I only dispose the objects I kept a reference to? or should I find a way to dispose all objects I created.

My code:

public class MyClass  
{  
    ClassThatIsDisposable aReference;  
}

public MyClass(ManagerClass manager)  
{  
    ClassThatIsDisposable transient=new ClassThatIsDisposable();  
    manager.Add(transient);  
    aReference=new ClassThatIsDisposable();  
    manager.Add(aReference);  
}

public void LaterCall()  
{  
    areference.Method();  
}  

The class that owns the object is the one that should dispose of them... It sounds like your manager is the owner, so he should dispose of the object.

If you're trying to avoid the FXCop warning then one option is to have MyClass request the disposable object from the manager each time is needs to use it. This way you won't have a member variable holding a reference to it. You could do this my having the Add() method return akey for the object that has been added and then use this key to retrieve the object from the manager when you need to use it.

If you create any disposable objects, you should either dispose them yourself or make sure you're handing them off to another class which will take responsibility for that.

In this case, I'd say it really depends on what the manager class is going to do. If that guarantees that it will dispose of anything that is added to it, you're okay. It does look like a somewhat odd design pattern though - I can't say I've used anything similar myself. That's not to say it's necessarily wrong/bad, but it would at least be worth taking another look to see if there's any way of avoiding this slight confusion of ownership.

Bear in mind that if the manager disposes the object you're holding a reference to, it's likely to be unusable afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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