Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who Disposes of an IDisposable public property?

If I have a SomeDisposableObject class which implements IDisposable:

class SomeDisposableObject : IDisposable {     public void Dispose()     {         // Do some important disposal work.     } } 

And I have another class called AContainer, which has an instance of SomeDisposableObject as a public property:

class AContainer {     SomeDisposableObject m_someObject = new SomeDisposableObject();      public SomeDisposableObject SomeObject     {         get { return m_someObject; }         set { m_someObject = value; }     } } 

Then FxCop will insist that AContainer is also made IDisposable.

Which is fine, but I can't see how I can safely call m_someObject.Dispose() from AContainer.Dispose(), as another class may still have a reference to the m_someObject instance.

What is the best way to avoid this scenario?

(Assume that other code relies on AContainer.SomeObject always having a non-null value, so simply moving the creation of the instance outside of the AContainer is not an option)

Edit: I'll expand with some example as I think some commenters are missing the issue. If I just implement a Dispose() method on AContainer which calls m_someObject.Dispose() then I am left with these situations:

// Example One AContainer container1 = new AContainer(); SomeDisposableObject obj1 = container1.SomeObject; container1.Dispose(); obj1.DoSomething(); // BAD because obj1 has been disposed by container1.  // Example Two AContainer container2 = new AContainer(); SomeObject obj2 = new SomeObject(); container2.SomeObject = obj2; // BAD because the previous value of SomeObject not disposed. container2.Dispose(); obj2.DoSomething(); // BAD because obj2 has been disposed by container2, which doesn't really "own" it anyway.   

Does that help?

like image 916
GrahamS Avatar asked Mar 23 '09 19:03

GrahamS


People also ask

What happens if you dont Dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.

Who calls the Dispose method?

Before the GC deallocates the memory, the framework calls the object's Finalize() method, but developers are responsible for calling the Dispose() method. The two methods are not equivalent. Even though both methods perform object clean-up, there are distinct differences between them.

Does garbage collector call Dispose C#?

The GC does not call Dispose , it calls your finalizer (which you should make call Dispose(false) ).

How do you Dispose of resources using dependency injection?

When you make it explicit, you've got basically two options: 1. Configure the DI to return transient objects and dispose these objects yourself. 2. Configure a factory and instruct the factory to create new instances.


1 Answers

There is no single answer, it depends on your scenario, and the key point is ownership of the disposable resource represented by the property, as Jon Skeet points out.

It's sometimes helpful to look at examples from the .NET Framework. Here are three examples that behave differently:

  • Container always disposes. System.IO.StreamReader exposes a disposable property BaseStream. It is considered to own the underlying stream, and disposing the StreamReader always disposes the underlying stream.

  • Container never disposes. System.DirectoryServices.DirectoryEntry exposes a Parent property. It is not considered to own its parent, so disposing the DirectoryEntry never disposes its parent.

    In this case a new DirectoryEntry instance is returned each time the Parent property is dereferenced, and the caller is presumably expected to dispose it. Arguably this breaks the guidelines for properties, and perhaps there should be a GetParent() method instead.

  • Container sometimes disposes. System.Data.SqlClient.SqlDataReader exposes a disposable Connection property, but the caller decides if the reader owns (and therefore disposes) the underlying connection using the CommandBehavior argument of SqlCommand.ExecuteReader.

Another interesting example is System.DirectoryServices.DirectorySearcher, which has a read/write disposable property SearchRoot. If this property is set from outside, then the underlying resource is assumed not to be owned, so isn't disposed by the container. If it's not set from outside, a reference is generated internally, and a flag is set to ensure it will be disposed. You can see this with Lutz Reflector.

You need to decide whether or not your container owns the resource, and make sure you document its behavior accurately.

If you do decide you own the resource, and the property is read/write, you need to make sure your setter disposes any reference it's replacing, e.g.:

public SomeDisposableObject SomeObject     {             get { return m_someObject; }             set      {          if ((m_someObject != null) &&              (!object.ReferenceEquals(m_someObject, value))         {             m_someObject.Dispose();         }         m_someObject = value;      }     } private SomeDisposableObject m_someObject; 

UPDATE: GrahamS rightly points out in comments that it's better to test for m_someObject != value in the setter before disposing: I've updated the above example to take account of this (using ReferenceEquals rather than != to be explicit). Although in many real-world scenarios the existence of a setter might imply that the object is not owned by the container, and therefore won't be disposed.

like image 56
Joe Avatar answered Sep 26 '22 08:09

Joe