Game Development Reference
In-Depth Information
// Perform cleanup here
Objects requiring finalization should be wrapped into the smallest object possible.
If your class accesses both managed and unmanaged memory, you should make a
child finalizer class that releases the unmanaged resources and encapsulates them
in the parent object. Keep in mind that in order for this to work, there cannot be
any strong references to the parent object.
Never implement a finalizer that blocks the finalization thread. Remember that there is only one
thread for it, and blocking this thread will prevent resources from being freed.
Finalization is a great feature to have, but it is also very important that you are
aware of the expensive performance implications. Another negative attribute of
finalization is that you do not really have control over when the finalizer will exe-
cute or when the garbage collector will perform cleanup. A solution to these problems
is to implement the dispose pattern which supports both the implicit and explicit
freeing of resources.
The Dispose Pattern
For situations where the lifetime of an object is explicitly known, the dispose pat-
tern is used to release unmanaged resources. Functionality for disposable objects
is implemented through the IDisposable interface by providing an implementation
for the Dispose method. In fact, you never know how your object will be used, so
implementing a finalizer and IDisposable is the proper way of handling the release
of unmanaged resources.
Both the finalizer and the Dispose method will call the same code, and it is advis-
able to route them both to the same function so that the code is maintainable and
in one place only. When the Dispose method is called, it is important to inform the
garbage collector that finalization is not needed. This is done by calling the
GC.SuppressFinalization method.
The following code shows the proper way to implement IDisposable with support
for finalization and multi-threading:
public class YourClass : IDisposable
Search Nedrilad ::

Custom Search