Tuesday, December 1, 2009

Life cycle of an object

  1. When the object is created, memory is allocated for it, the constructor is run, and the object is considered live.
  2. If the object, or any part of it, cannot be accessed by any possible continuation of execution, other than the running of destructors, the object is considered no longer in use and it becomes eligible for destruction.
  3. The C# compiler and the garbage collector may choose to analyze code to determine which references to an object may be used in the future. For instance, if a local variable that is in scope is the only existing reference to an object, but that local variable is never referred to in any possible continuation of execution from the current execution point in the procedure, the garbage collector may (but is not required to) treat the object as no longer in use.
  4. Once the object is eligible for destruction, at some unspecified later time the destructor (if any) for the object is run. Unless overridden by explicit calls, the destructor for the object is run once only.
  5. Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any possible continuation of execution, including the running of destructors, the object is considered inaccessible and the object becomes eligible for collection.
  6. Finally, at some time after the object becomes eligible for collection, the garbage collector frees the memory associated with that object.
The behavior of the garbage collector can be controlled, to some degree, via static methods on the class System.GC. This class can be used to request a collection to occur, destructors to be run (or not run), and so forth.
Note:
Destructors are not inherited. Thus, a class has no destructors other than the one that may be declared in that class.

Since a destructor is required to have no parameters, it cannot be overloaded, so a class can have, at most, one destructor.
Destructors are invoked automatically, and cannot be invoked explicitly. An instance becomes eligible for destruction when it is no longer possible for any code to use that instance. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.  (http://www.devx.com/dotnet/Article/33167/1954)

No comments: