Garbage collection is a
technique meant to avoid those types of bugs, since the execution environment now handles the
tracking of object references and destroys the object instances when they??™re no longer in use.
The CLR tracks every managed object reference in the system. Once the CLR realizes that
an object is no longer reachable via a reference, it flags the object for deletion. The next time
the garbage collector compacts the heap, these flagged objects either have their memory
reclaimed or are moved over into a queue for deletion if they have a finalizer. It is the responsibility
of another thread, the finalizer thread, to iterate over this queue of objects and call their
finalizers before freeing their memory. Once the finalizers have completed, the memory for
the object is freed on the next collection pass and the object is destroyed.
Finalizers
Like the constructor New(), the destructor Finalize() is created implicitly when you create an
object and, by default, doesn??™t do anything. When used flagrantly and unnecessarily, finalizers
can degrade the performance of the CLR because finalizable objects live longer than their
nonfinalizable counterparts. Even allocating finalizable objects is more costly. Finalizers are
difficult to write because you cannot make any assumptions about the state other objects in
the system are in.
Pages:
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131