当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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?

网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: