What are the methods to destroy Excel COM Interop objects in C#, besides these:
object_instance = null;
System.GC.collect();
&
System.Runtime.InteropServices.Marshal.ReleaseComObject(object);
Please suggest only inbuilt techniques, not other tools like bigcannon, etc.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
Just as constructor functions create objects, destructor functions destroy objects.
delete keyword in C++Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.
Question: How does a program destroy an object that it creates? Answer: A program does not explicitly destroy objects. A program can set all references to an object to null so that it becomes eligible for garbage collection. But the program does not actually destroy objects.
The kicker is that if you haven't dropped all references to the object, even GC.Collect won't destroy it.
The rule in C# (or .NET generally) is that you can't destory an object. Dispose() won't do it. A finalizer won't do it (rule number 2, don't use a finalizer unless you know why you need it, and don't ever call it directly).
For .NET, these are the things you need to do:
The garbage collector is the only mechanism that can destroy a managed object, but you usually don't invoke it explicitly. You just let it do its thing.
Just like you never take your own trash to the depot, you just leave it sitting on the corner. It's always the garbage man's responsibility.
You can release references to things and clean them up with IDisposable, finalizers and destructors but not destroy them.
By using System.GC you can ask the garbage man to do things early - request a custom run just for yourself - but this usually screws up his schedule and he has a lot more trash to deal with than just yours so it's not recommended.
For the most part, you have to remove all references to an object. Only then will the garbage collector see it and destroy it.
Be aware of this:
object_instance = null;
All this does is kill the object_instance reference. This works if it's the only reference. If there are other references, then it won't be collected.
var skywalker = new Person();
var object_instance = skywalker;
...
object_instance = null;
//It's still alive and won't be collected because skywalker lives...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With