Tuesday, April 2, 2013

Lifetime of a static class/variable

Ever felt a need to keep the values in a static class for a longer time before the garbage collector picks it up....

Here is an excerpt from SAP Help to achieve this


Object Lifetime

An object exists for as long as it is being used in the program. An object is in use by a program for as long as at least one reference points to it, or at least one method of the object is registered as an event handler.
As soon as there are no more references to an object, and so long as none of its methods are registered as event handlers, it is deleted by the automatic memory management (garbage collection). The ID of the object then becomes free, and can be used by a new object.

The trick is make your class an event handler for a Event of the main object - and yes this only works if there is some main object.