Handling events
One of the most common causes of memory leaks appearing in an application is the failure to remove event handlers once objects are no longer needed. When we attach an event handler to an object's event in the usual way, we are effectively passing that object a reference to the handler and creating a hard reference to it.
When the object is no longer needed and could otherwise be disposed of, the reference in the object that raises the event will prevent that from occurring. This is because the garbage collector cannot collect an object that can be accessed from any part of the application code. In the worst case scenario, the object being kept alive may contain numerous other objects and so inadvertently keep them alive also.
The problem with this is that keeping objects alive after they are no longer needed will unnecessarily increase the memory footprint of the application, in some cases, with dramatic and irreversible consequences, leading to an OutOfMemoryException
being...