Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose managed resource in Dispose() method in C#?

I know Dispose() is intended for unmanaged resource, and the resource should be disposed when it is no longer needed without waiting for the garbage collector to finalize the object.

However, when disposing the object, it suppress finalization of the garbage collector (GC.SuppressFinalize(this); in the code below). This means that if the object includes managed resource, we will have to take care of that too because garbage collector will not clean this up.

In the example code below (from MSDN), "Component" is a managed resource, and we call dispose() for this resource (component.Dispose()). My question is, how do we implement this method for Component class which is managed resource? Should we use something like Collect() to poke garbage collector to clean this portion?

Any idea would be appreciated. Thanks.

Below is the code I'm looking at which is from MSDN:

using System;
using System.ComponentModel;

// The following example demonstrates how to create
// a resource class that implements the IDisposable interface
// and the IDisposable.Dispose method.

public class DisposeExample
{
// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public class MyResource: IDisposable
{
    // Pointer to an external unmanaged resource.
    private IntPtr handle;
    // Other managed resource this class uses.
    private Component component = new Component();
    // Track whether Dispose has been called.
    private bool disposed = false;

    // The class constructor.
    public MyResource(IntPtr handle)
    {
        this.handle = handle;
    }

    // Implement IDisposable.
    // Do not make this method virtual.
    // A derived class should not be able to override this method.
    public void Dispose()
    {
        Dispose(true);
        // This object will be cleaned up by the Dispose method.
        // Therefore, you should call GC.SupressFinalize to
        // take this object off the finalization queue
        // and prevent finalization code for this object
        // from executing a second time.
        GC.SuppressFinalize(this);
    }

    // Dispose(bool disposing) executes in two distinct scenarios.
    // If disposing equals true, the method has been called directly
    // or indirectly by a user's code. Managed and unmanaged resources
    // can be disposed.
    // If disposing equals false, the method has been called by the
    // runtime from inside the finalizer and you should not reference
    // other objects. Only unmanaged resources can be disposed.
    private void Dispose(bool disposing)
    {
        // Check to see if Dispose has already been called.
        if(!this.disposed)
        {
            // If disposing equals true, dispose all managed
            // and unmanaged resources.
            if(disposing)
            {
                // Dispose managed resources.
                component.Dispose();
            }

            // Call the appropriate methods to clean up
            // unmanaged resources here.
            // If disposing is false,
            // only the following code is executed.
            CloseHandle(handle);
            handle = IntPtr.Zero;

            // Note disposing has been done.
            disposed = true;

        }
    }

    // Use interop to call the method necessary
    // to clean up the unmanaged resource.
    [System.Runtime.InteropServices.DllImport("Kernel32")]
    private extern static Boolean CloseHandle(IntPtr handle);

    // Use C# destructor syntax for finalization code.
    // This destructor will run only if the Dispose method
    // does not get called.
    // It gives your base class the opportunity to finalize.
    // Do not provide destructors in types derived from this class.
    ~MyResource()
    {
        // Do not re-create Dispose clean-up code here.
        // Calling Dispose(false) is optimal in terms of
        // readability and maintainability.
        Dispose(false);
    }
}
public static void Main()
{
    // Insert code here to create
    // and use the MyResource object.
}
}
like image 200
Will Yeo - MSFT Avatar asked Feb 17 '10 21:02

Will Yeo - MSFT


People also ask

How do you use the Dispose method?

The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

What is Dispose () and Finalize ()?

Finalize is the backstop method, called by the garbage collector when it reclaims an object. Dispose is the "deterministic cleanup" method, called by applications to release valuable native resources (window handles, database connections, etc.)

Which method is overridden to clean up UN managed resources?

Dispose implementation directly to free memory used by unmanaged resources. When you properly implement a Dispose method, either your safe handle's Finalize method or your own override of the Object. Finalize method becomes a safeguard to clean up resources in the event that the Dispose method is not called.


1 Answers

That disposable pattern is confusing. Here's a better way to implement it:

Step 1. Create a disposable class to encapsulate each unmanaged resource that you have. This should be really rare, most people don't have unmanaged resources to clean up. This class only cares (pdf) about its unmanaged resource, and should have a finalizer. The implementation looks like this:

public class NativeDisposable : IDisposable {

  public void Dispose() {
    CleanUpNativeResource();
    GC.SuppressFinalize(this);
  }

  protected virtual void CleanUpNativeResource() {
    // ...
  }

  ~NativeDisposable() {
    CleanUpNativeResource();
  }

  // ...

  IntPtr _nativeResource;

}

Step 2. Create a disposable class when the class holds other disposable classes. That's simple to implement, you don't need a finalizer for it. In your Dispose method, just call Dispose on the other disposables. You don't care about unmanaged resources in this case:

public class ManagedDisposable : IDisposable {

  // ...

  public virtual void Dispose() {
    _otherDisposable.Dispose();
  }

  IDisposable _otherDisposable;

}

The "Component" in the example would be either one of these, depending on whether it encapsulates an unmanaged resource or if it is just composed of other disposable resources.

Also note that supressing finalization does not mean you're suppressing the garbage collector from cleaning up your instance; it just means that when the garbage collector runs in your instance, it will not call the finalizer that's defined for it.

like image 150
Jordão Avatar answered Sep 20 '22 12:09

Jordão