When the finalization thread iterates through the objects in the finalization
queue, it calls the Finalize() method on each object. The Finalize() method has no return
type and accepts no parameters.
Although the garbage collector now handles the task of cleaning up memory so that you
don??™t have to worry about it, you have a whole new host of concerns to deal with when it
comes to the destruction of objects. A short while ago, we mentioned that finalizers run on a
separate thread in the CLR. Therefore, whatever objects you use inside your destructor must
be thread-safe. You should not use other objects in your finalizer, as they may have already
been finalized or destroyed. This includes objects that are fields of the class that contains the
finalizer. You have no guaranteed way of knowing exactly when the garbage collector will call
your finalizer or in what order the finalizer will be called between two independent objects.
This is one more reason why you shouldn??™t introduce interdependencies on objects in
the destructor code block. After all this dust has settled, it starts to become clear that you
shouldn??™t do much inside a finalizer except basic housecleaning, if anything.
CHAPTER 3 n CLASSES AND STRUCTURES 62
There are times when you should explicitly create a finalizer.
Pages:
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132