0

I have a C# project in which managed C++ class is used. This managed C++ class is wrapping an unmanaged C++ code.

I have code block like this;

if (true)
{
                ManagedFoo foo = new ManagedFoo();                
}

//GC.Collect(); // I also tried with this one but result is same

I have placed a simple output string to destructor of class.

If I run program from visual studio, destructor of foo is not called. But if I run program by double clicking on it(it is a console application), destructor is called immediately.

Why it is behaving like this?

Many thanks, Regards

OregonGhost
  • 23,359
  • 7
  • 71
  • 108
AFgone
  • 1,172
  • 4
  • 16
  • 31
  • duplicate from http://stackoverflow.com/questions/755680/gc-collect-doesnt-seem-to-work-in-debug-mode ? – nob Aug 26 '10 at 08:25

1 Answers1

1

I could be wrong, but aren't C++ destructors mapped to IDisposable.Dispose in C++/CLI? If so, you have to call Dispose or rather wrap it in a using block, just like with any other IDisposable:

using (ManagedFoo foo = new ManagedFoo()) {
    /// Use foo in here
}

The question linked by nob explains why the behaviour may be different between debugging and running directly. I bet the destructor is called in the finalizer, if you didn't call it explicitly.

OregonGhost
  • 23,359
  • 7
  • 71
  • 108