Subscribe

RSS Feed (xml)

C# Overriding Dispose - bool

The version of the CipherComp component just shown does not hold any system resource, nor does it create and hold any objects. For these reasons, it was not necessary to override Dispose(bool). However, if your component does hold resources, then you will usually need to override Dispose(bool) so that the resources can be freed in a deterministic fashion. Fortunately, this is easy to do.

Before we begin, it is important to understand why a component will usually need to free its own resources, rather than relying on the normal C# garbage collection mechanism. As explained earlier in this book, as far as your program is concerned, garbage collection is a non-deterministic occurrence. It happens as needed (or when otherwise deemed appropriate by the garbage collector) and not just because objects are available to recycle. Thus, if a component holds a resource, such as an open file, which needs to be released in order for it to be used by another program, there must be some way to deterministically release these resources when a client is done using the component. Simply removing all references to the component does not solve the problem, because the component will still be holding a reference to the needed resource until the next time garbage is collected. The solution is for the component to implement Dispose(bool).

When overriding Dispose(bool), you must follow a few rules:

  1. When Dispose(bool) is called with a true argument, your version must release all resources, both managed and unmanaged, associated with the component. When it is called with a false argument, your version must release only the unmanaged resources, if any.

  2. Dispose(bool) must be able to be called repeatedly, without harm.

  3. Dispose(bool) must call the base class implementation of Dispose(bool).

  4. The destructor for your component should simply call Dispose(false).

To satisfy rule 2, your component will need to keep track of when it has been disposed. This is usually done by maintaining a private field that indicates the disposed status.

Here is a skeletal component that implements Dispose(bool):

// A skeletal implementation of a component that uses Dispose(bool).
class MyComp : Component {
  bool isDisposed; // true if component is disposed

  public MyComp() {
    isDispose = false;
    // ...
  }

  ~MyComp() {
    Dispose(false);
  }

  protected override void Dispose(bool dispAll) {
    if(!isDisposed) {
      if(dispAll) {
        // release managed resources here
        isDisposed = true; // set component to disposed
      }
      // release unmanaged resources here
      base.Dispose(dispAll);
    }
  }
}

When you call Dispose( ) on an instance of a component, Dispose(bool) is automatically called to clean up any resources owned by the component.

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail