Instance Finalizers

Instance Finalizers

Another special method characteristic of a class instance is a finalizer, which is in many aspects similar to a C++ destructor. The finalizer must have the following signature:

.method family virtual instance void Finalize( ) {     }

Unlike instance constructors, which cannot be virtual, instance destructors—sorry, I mean finalizers—must be virtual. This requirement and the strict limitations imposed on the finalizer signature and name result from the fact that any particular finalizer is an override of the virtual method Finalize of the inheritance root of the class system, the [mscorlib]System.Object class, the ultimate ancestor of all classes in the Microsoft .NET universe. To tell the truth, the Object’s finalizer does exactly nothing. But Object, full of fatherly care, declares this virtual method anyway, so Object’s descendants could override it, should they desire to do something meaningful at the inevitable moment of their instances’ demise.

The finalizer is executed by the garbage collection (GC) subsystem of the runtime when that subsystem decides that a class instance should be disposed of. No one knows exactly when this happens; the only solid fact is that it occurs after the instance is no longer used and has become inaccessible. But how soon after is anybody’s guess.

If you prefer to execute the instance’s last will and testament—that is, call the finalizer—when you think you don’t need the instance any more, you can do exactly that by calling the finalizer explicitly. But then you should notify the GC subsystem that it does not need to call the finalizer again when in due time it decides to dispose of the abandoned class instance. You can do this by calling the .NET Framework class library method [mscorlib]System.GC::SuppressFinalize, which takes the object (a reference to the instance) as its sole argument—the instance is still there; you simply called its finalizer but did not destroy it—and returns void.

If for some reason you change your mind afterward, you can notify the GC subsystem that the finalizer must be run after all by calling the [mscorlib]System.GC::ReRegisterForFinalize method with the same signature, void(object). You needn’t fear that the GC subsystem might destroy your long-suffering instance without finalization before you call ReRegisterForFinalize—as long as you can still reference this instance, the GC will not touch it. Both methods for controlling finalization are public and static, so they can be called from anywhere.



Inside Microsoft. NET IL Assembler
Inside Microsoft .NET IL Assembler
ISBN: 0735615470
EAN: 2147483647
Year: 2005
Pages: 147
Authors: SERGE LIDIN

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net