0

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.

user1289479
  • 291
  • 4
  • 16
  • Finalizers are only called when the object is GC'd, where did you read that it is called when it is disposed? I also don't think that .NET generates a Disposable call for objects that don't have them. If there is no memory pressure, the object won't get finalized, that is how GC works. – Ron Beyer Jun 27 '19 at 18:18
  • I said destructor not finalizer. I know that the finalizer is only called by the garbage collector, but my thing is that I called Dispose in C#, but my breakpoints in CLI is not getting hit. From everything I read, it seemed that the ~ClassA breakpoint should be hit, but it's not. – user1289479 Jun 27 '19 at 18:24
  • How is your C# project getting a reference to the C++/CLI assembly? Are you sure `wrapper.Data` is actually an instance of `ClassA` and not some other class which implements `IDisposable`? I was able to hit breakpoints in `ClassA::~ClassA`. I had both projects in the same solution, and added the CPP/CLI project as a Project Reference to the C# project. – Joshua Robinson Jun 27 '19 at 18:57
  • They do live in different projects but in the same solution. I know it is of ClassA because I put a breakpoint in there and when i hovered over disposable, the Visual Studio debugger told me it was a type of ClassA. – user1289479 Jun 27 '19 at 20:11

1 Answers1

0

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)

user1289479
  • 291
  • 4
  • 16