Best way to prevent early CLR garbage collection
I wrote a managed class that wraps an unmanaged C ++ object, but I found that - when using it in C # - the GC starts early while I execute a method on the object. I've read through garbage collection and how to prevent it before. One way is to use a using statement to control when the object is placed, but this puts the responsibility on the client of the managed object. I can add to the managed class:
MyManagedObject::MyMethod()
{
System::Runtime::InteropServices::GCHandle handle =
System::Runtime::InteropServices::GCHandle::Alloc(this);
// access unmanaged member
handle.Free();
}
code> This works. As a newbie to .NET, how do other people deal with this problem?
Thanks,
Johan
a source to share
You may like to check out this article: http://www.codeproject.com/Tips/246372/Premature-NET-garbage-collection-or-Dude-wheres-my . I believe this accurately describes your situation. In short, remedies are a block using
or GC.KeepAlive
. However, I agree that in many cases you will not want to delegate this burden to the client of the unmanaged object; in this case, calling GC.KeepAlive (this) at the end of each wrapper method is a good solution.
a source to share
You can use GC.KeepAlive(this)
in your method body if you want the finalizer not to be called. As others note in the comments, if your reference is this
not being used during a method call, it is possible that the finalizer will be called and memory reclaimed during the call.
See http://blogs.microsoft.co.il/blogs/sasha/archive/2008/07/28/finalizer-vs-application-a-race-condition-from-hell.aspx for details .
a source to share