• Embed Doc
  • Readcast
  • Collections
  • CommentGo Back
Download
 
You must implement finalizers very carefully; it's a complex operation that can carry considerableperformance overhead. The performance overhead stems from the fact that finalizable objectsare enlisted and removed from the
finalization queues
, which are internal data structurescontaining pointers to instances of classes that implement a finalizer method. When pointers tothese objects are placed in this data structure, the object is said to be enlisted in the FinalizationQueue. Note that the GC periodically scans this data structure to locate these pointers. When itfinds one, it removes the pointer from the queue and appends the pointer at the end of another queue called the f 
reachable queue
.Further, finalizable objects tend to get promoted to the higher generations and hence stay inmemory for a relatively longer period of time. Note that the GC works more frequently in the lower generations than in the higher ones.The time and order of execution of finalizers cannot be predicted or pre-determined. This is whyyou'll hear that the nature of finalization is "non-deterministic." Further, due to the non-deterministic nature of finalization the framework does not and cannot guarantee that the
Finalize
method will ever be called on an instance. Hence, you cannot rely upon this method to free upany un-managed resources (such as a file handle or a database connection instance) that wouldotherwise not be garbage collected by the GC.Note that you cannot call or override the
Finalize
method. It is generated implicitly if you have adestructor for the class. This is shown in the following piece of C# code:—
class Test{ // Some Code ~Test{//Necessary cleanup code}} 
In the preceding code, the
~Test 
syntax declares an explicit destructor in C#, letting you writeexplicit cleanup code that will run during the finalize operation.The framework implicitly translates the explicit destructor to create a call to
Finalize
:
protected override void Finalize(){try{//Necessary cleanup code}finally{base.Finalize();}} 
Note that the generated code above calls the
base.Finalize
method.You should note the following points should when implementing finalizers:
of 00

Leave a Comment

You must be to leave a comment.
Submit
Characters: ...
You must be to leave a comment.
Submit
Characters: ...