C# - 3 - Delegated events in MVC.

[C# 2.0]

Apart from not disposing of disposable objects, another source of memory leaks are event handlers. If, for example, a form has delegated event handlers that have been latched onto by a controller (in the MVC pattern) then that form will leak … even if disposed of and no references exist to it. Let's assume that in the form we have a private event called _MyFormLoading which is delegated out as a public event called MyFormLoading.

In the controller, coding …

… achieves nothing.

Instead, look at the form's Dispose() method (by default it's in the form's designer file).

Some people think that as the designer file is autogenerated it shouldn't be changed, but in fact that rule only applies to the code the immediately following the Dispose() method. Rewrite the method like this:

(Note that the events are removed with ''='' and not a ''-=''. Also note that the check for components being null is moved down so as not to apply to the event lines.)


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License