views:

30

answers:

2

Hello, 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

A: 

duplicate from http://stackoverflow.com/questions/755680/gc-collect-doesnt-seem-to-work-in-debug-mode ?

nob
I tried both in release and debug mode but results are same. Destructor is called only if I run the application outside the IDE.
AFgone
+1  A: 

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