Finalizer (keyword)
From The Oxygene Language Wiki
This is a Language topic
Feel free to add your notes to this topic below.
Finalizers are defined with the finalizer keyword:
type MyClass = class public ... finalizer; end; ... finalizer MyClass; begin ... // cleanup goes here end;
Optionally you can also add the name "Finalize" to the declaration, as in:
type MyClass = class public ... finalizer Finalize; end; ... finalizer MyClass.Finalize; begin ... // cleanup goes here end;
Delphi Prism will automatically create a try/finally block around the entire code body and call the inherited finalizer at the end.
Finalizers are always protected/override, no matter where they are declared.
Finalizers automatically call "inherited finalizer;" (in a try/finally block), so there is no need to do this manually.
Implementing IDisposable
When writing classes that hold either managed or unmanaged resources, such as file, window or database handles, streams or instances of other classes that also implement IDisposable, Microsoft recommends that you follow a "pattern" to ensure that resources are neither left unreleased or released more than once.
type MyClass = class(IDisposable) private disposed: Boolean; method Dispose(disposing: Boolean); public ... method Dispose; finalizer Finalize; end; ... method MyClass.Dispose; begin Dispose(true); GC.SuppressFinalize(self); end; method MyClass.Dispose(disposing: Boolean); begin if not disposed then begin if disposing then begin // Dispose of managed resources. end; // Dispose of unmanaged resources disposed := true; end; end; finalizer MyClass.Finalize; begin Dispose(false); end;
Notes
Only supply finalizers when they are really needed, as there is a performance penalty associated with them (garbage collector actually has to make two passes). Be particularly careful here if there are many object instances created, as the finalizer code will get called for each one.
Resources used by managed objects are reclaimed by the garbage collector. Any class that creates unmanaged resources (e.g. a socket, file, mutex etc.), however needs to provide a Finalizer to free them, if this needs to be done before the application terminates.
You should regard finalizer code as a request to free resources, as this will only happen on the next pass of the garbage collector. This, of course, is not good for things like files. Add the IDisposable interface in this case and free your file with the Dispose method.
See Also
Area: Oxygene Language
Compiler version: Oxygene 5
Language Glossary — Keywords — Types — FAQ — How To