CleanForFree is a lifecycle method for developers who subclass MDriven Framework types and need to release references when an instance has been determined never to be used again.
Purpose
Implement CleanForFree when your subclass keeps references to other objects that should no longer remain connected after the instance is finished.
The method is part of the MDriven Framework cleanup pattern. It is called after it has been decided that the object will never be used again. At that point, release the references retained by the object so the garbage collector can recognize the disconnected object structure as eligible for collection sooner.
CleanForFree and Dispose
CleanForFree is a softer form of disposal. Its purpose is to break retained connections in an object graph rather than leave large structures connected through references that are no longer needed.
| Method | Use in this pattern |
|---|---|
CleanForFree
|
Release references held by the object after it is known to be finished. This helps large connected structures decompose for garbage collection. |
Dispose
|
Represents the stronger disposal concept. CleanForFree is described as a softer version of Dispose. |
When to implement it
Implement CleanForFree if all of the following apply:
- Your type subclasses an MDriven Framework type.
- Your subclass retains references to other objects or object structures.
- Those references are no longer needed once the instance has been marked as never to be used again.
If the subclass does not retain references that need releasing, there may be no subclass-specific cleanup to perform.
What cleanup should do
In CleanForFree, release the references that your subclass has kept and that are no longer required after the object has finished its lifecycle.
For example, assume an object retains a reference to a large structure of related objects. Even when the original object is no longer useful, that retained reference can keep the structure connected. Releasing the reference in CleanForFree disassembles that connection, allowing the garbage collector to classify the now-disconnected objects as deleted faster than if the structure remained connected.
Think of the method as taking apart a large piece of normal garbage before it is collected: the objects are no longer useful, and removing the remaining connections makes the structure easier to decompose.
Lifecycle boundary
Do not treat CleanForFree as ordinary application logic. It runs at the point where the object has already been determined never to be used again. Cleanup performed here must therefore be limited to releasing references that the object no longer needs.
