简体   繁体   中英

How to correctly implement disposable pattern with third-party libraries

Suppose that I have the following classes:

class Foo : IDisposable
{
  public void Dispose()
  {
    bar.Dispose();
  }

  private Bar bar = new Bar();
}

class Bar : IDisposable
{
  public void Dispose()
  {
    baz.Dispose();
  }

  private SomeThirdPartyLibraryClass baz = new SomeThirdPartyLibraryClass();
}

This code works well when using using statement:

using (Foo foo = new Foo())
{
  // ...
}
// All resources should be disposed at this time

However, if for some reason user of this class forgot to use using statement, resources will never be disposed.

According to MSDN, I should implement disposable pattern in the following manner:

class Foo : IDisposable
{
  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  protected virtual void Dispose(bool disposing)
  {
    if (disposed)
      return; 

    if (disposing) {
      // Free any managed objects here.
      //
    }

    // Free any unmanaged objects here.
    //
    disposed = true;
  }

  ~Foo()
  {
    Dispose(false);
  }

  bool disposed = false;
  private Bar bar = new Bar();
}

(the same goes for Bar )

But where exactly should I place bar.Dispose(); and baz.Dispose(); code?

Should it be under "managed cleanup" section or under "unmanaged cleanup" section?

As the name suggests, I don't know the implementation of SomeThirdPartyLibraryClass (and anyway, it can be changed over time).

What should I do then?

But where exactly should I place bar.Dispose(); and baz.Dispose(); code?

As your third party library seems to be managed code, it would go in the "managed cleanup" section.

You should be calling Dispose of bar and baz under the managed section of Dispose because for your class they are managed objects. If bar and baz have something unmanaged then that should get cleaned up by their respective classes in their Dispose/Finalize implementation.

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