Search code examples
c#.netc++-clidispose

C++/CLI Destructor not called when Dispose is called in C#


So I have a C++/CLI object held inside a C# object. I am calling dispose on my C++/CLI object and I have a breakpoints in both C++/CLI destructor and finalizer.

I know that .NET should auto generate a Dispose for CLI objects and put the destructor in there, but my breakpoint in the destructor is just not getting hit. Can someone explain what is going to me because I haven't been able to find any documentation of this behaviour.

C#

public void Dispose()
{
    foreach (var wrapper in m_items)
    {
        var disposable = wrapper.Data as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
}

C++/CLI

public ref class ClassA: System::IDisposable {
...
    ClassA::~ClassA()
    {
        // Clean up code
    }

    ClassA::!ClassA()
    {
        // Clean up code
    }
}

I apologize if this question has been answered already, but I have tried and couldn't find it on stack overflow.


Solution

  • Ahhh found out why, turns out even though I had optimization off in Visual Studio, it auto optimized out my Destructor into the 1 function call I had in the Destructor.

    So even though the breakpoint looked valid I had to put a breakpoint in my other function to get the call stack. (Interesting bit was the call stack went directly from Dispose(bool) to my function and skipped the destructor)