Game Development Reference
In-Depth Information
The CLR does not use reference counting, so finalization was created to accom-
modate the issue behind releasing resources when references reach zero.
Finalization is used in situations where an object's lifetime is unknown and the
object requires cleanup.
The finalization mechanism increases the level of exertion required by the garbage
collector, so it should be used appropriately. Objects requiring finalization are
entered in a finalizable queue (f-reachable) that is searched by the garbage collec-
tor during a collection. The garbage collector manages a separate finalizer thread
that processes objects that require finalization. Objects being finalized are moved
into the next generation because the garbage collector may require their state. The
memory for finalized objects will be released during the following collection.
There are two ways to implement finalization, each accomplishing the same thing
but using different syntax. The first approach is overriding the Finalize method
available to any object. This approach is illustrated by the following code:
public class YourClass
{
public YourClass ()
{
}
protected override void Finalize()
{
// Perform cleanup here
}
}
The other method to implement finalization is using the same syntax that C++
uses for class destructors. It is important to know that even though the syntax is
identical, the C# version does not fire when the object goes out of scope. Instead,
it fires when the finalization thread gets around to releasing the object. This
approach is illustrated by the following code:
public class YourClass
{
public YourClass ()
{
}
~YourClass()
{
Search Nedrilad ::




Custom Search