2

My C# class creates and uses Managed C++ object that wraps (allocates and uses) unmanaged C++ objects and resources. The Managed C++ class correctly implements IDisposable with Destructor and Finalizer. Therefore, it appears that my C# class should also implement IDisposable. I want to follow correct IDisposable pattern in C# as well.

The following is unclear to me:

  • Within Dispose method of my C# class, should I treat my Managed C++ objects as managed or unmanaged (since they rely on unmanaged resources internally)?

1 Answer 1

4

Yes, your C# class should implement IDisposable as well. Its Dispose() method should simply dispose the C++/CLI objects. No need for a finalizer, you already implemented one in your wrappers. Your wrappers are no different from many other .NET classes that wrap an operating system resource.

For example:

class Test : IDisposable {
    private CppWrapper obj;
    //...
    public void Dispose() {
       if (obj != null) { 
           obj.Dispose();
           obj = null;
       }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry, please clarify. If the following is my C# code, in which section A or B should I dispose of my managed C++ classes? class Test : IDisposable { private bool isDisposed = false; ~Test() {Dispose(false);} protected void Dispose(bool disposing) { if (disposing) { // Section A. Dispose the managed resources } // Section B. Dispose the un-managed resources isDisposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } }
No, there is no need for this pattern since you don't have a finalizer. Thus no need to call GC.SuppressFinalize() and Dispose can never be called with disposing set to false. Which keeps it simple, I posted a snippet.
Thanks a lot Hans. However, I quote: "Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose". If so, why not have a Finalizer?
Because your C++/CLI class wrappers are the ones that own the unmanaged resource. You gave them a finalizer. That's enough to ensure that the unmanaged resource will always be released, even if the client programmer forgets to call Dispose() on your C# class.
OK, I understand now. Thank you once more Hans. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.