0

Is it possible to completely turn off garbage collection in C#? I'm debugging some hairy managed/native interop memory errors and I'd like to quickly rule out the possibility that GC is freeing native objects that I still need.

6
  • 3
    As the GC never frees native objects (well, not directly anyway), you can skip this test. How about posting the error and the code which causes it? Aug 24, 2013 at 17:45
  • Not sure what you mean, GC collects only when object goes out of the scope. Why do you leave objects out of scope when you need them? Aug 24, 2013 at 17:49
  • I use SWIG to create C# wrappers around C++ classes. The C# wrapper deletes the native object when it's collected. Other C++ objects can acquire native pointers to the wrapped object, which become invalid if C# collects it. Really not sure why everyone is trying to go off on tangents when the question I asked is so simple and direct.
    – japreiss
    Aug 24, 2013 at 17:51
  • @japreiss: Because the question sounds misinformed on its face. That sounds like an awfully error prone design btw. Aug 24, 2013 at 18:05
  • @Ed S. I agree, unfortunately it is beyond my control. Acquiring grey hairs from it regularly.
    – japreiss
    Aug 24, 2013 at 18:06

1 Answer 1

8

That's not possible.

Testing for this kind of bug scenario is done exactly the opposite way: you force a garbage collection before or after the interop call.

That's built into the debugger. It has two managed debugging assistants that can force a GC on an interop transition, gcManagedToUnmanaged and gcUnmanagedToManaged. Enable them in your .config file as shown in the linked article.

Not the answer you're looking for? Browse other questions tagged or ask your own question.