Reputation: 329
Is there any way that we can tell the garbage collector to not clean up certain resources in dot net. I mean I need certain managed resource to be clean and certain not. I don't have any practical scenario. But just wanted to know whether it is possible or not.
Thanks.
Upvotes: 0
Views: 108
Reputation: 941635
Other than simply storing a reference to the object in a static variable, you can always use GCHandle to add a reference. Use its Alloc() method.
That is however a bit of a chicken-and-egg problem, if you ever want to release the reference then you need to store the GCHandle somewhere so you can call its Free() method. It is really only practical in interop scenarios where unmanaged code indirectly references the object, usually through a delegate. The GC cannot see such a reference so an explicit one has to be created, GCHandle is good for that. Otherwise the only reason I can think of for asking this question, this really does require a practical usage.
Upvotes: 2
Reputation: 24078
If your object is still being referenced it won't be collected. Otherwise you can tell the Garbage Collector to keep the object alive with the GC.KeepAlive()
method.
References the specified object, which makes it ineligible for garbage collection from the start of the current routine to the point where this method is called.
Upvotes: 1