Information About

Finalizer




Unlike destructors, finalizers are not deterministic. A destructor is run when the programming explicitly frees an object. A finalizer, by contrast, is executed when the internal garbage collection system frees the object.

Programming languages which use finalizers include Java and C# . In C#, and a few others which support finalizers, the Syntax for declaring a finalizer mimics that of destructors in C++ .

Due to the lack of programmer control over their execution, it is usually recommended to avoid finalizers for any but the most trivial operations. In particular, operations often perfomed in destructors are not usually appropriate for finalizer. For example, destructors are often used to free expensive resources such as file or network handles. If placed in a finalizer, the resources may remain in use for long periods of time after the program is finished with them. Instead, most languages encourage a "dispose" Design Pattern whereby the object has a method to clean up the object's resources, leaving the finalizer as a fail-safe in the case where the dispose method doesn't get called. (The C# language supports the dispose pattern implicitly, via the IDisposable interface and the using Keyword .)


SEE ALSO