Friday, August 5, 2011

Why Use the Garbage Collector?

You can never destroy an object yourself by using C# or Visual Basic code. There are
good reasons why the designers of the .NET Framework decided to forbid you from
doing it. If it was your responsibility to destroy objects.

Following situations would arise:
• You would forget to destroy the object. This would mean that the object’s destructor
would not be run, tidying up would not occur, and memory would not be deallocated
back to the heap. You could quite easily run out of memory.
• You might try to destroy an active object. Remember that objects are accessed by
reference. If an object holds a reference to another object that you have previously
destroyed, this reference ends up referring either to unused memory or possibly to a
completely different object that happens to be allocated the same piece of memory. In
either case, the outcome of using this reference would be undefined at best or a
security risk at worst.
• You might try to destroy the same object more than once. This might or might not be
disastrous, depending on the code in the destructor.

These problems are unacceptable in code that is designed to be executed in a verifiable
manner by the CLR, which places robustness and security high on its list of design goals.
Instead, the garbage collector is responsible for destroying objects for you.

The garbage collector makes the following guarantees:
• Every object will be destroyed and its destructors run. When a program ends, all
outstanding objects will be destroyed.
• Every object will be destroyed exactly once.
• Every object will be destroyed only when it becomes unreachable—that is, when no
references refer to the object.

Note:- You can invoke the garbage collector in a program by calling the System.GC.Collect static method. However, except in a few cases, this is not recommended. The System.GC.Collect method starts the garbage collector, but the process runs asynchronously and, when the method call is complete, you still do not know whether your objects have been destroyed. Let the CLR decide when it is best to collect garbage.

One feature of the garbage collector is that you do not know, and should not rely upon, the order in which objects are destroyed. The final point to understand is arguably the most important: destructors do not run until objects are garbage collected. If you write a destructor, you know that it will be executed, but you do not know when.

No comments:

Recent Posts