1 minute read

Static events in user controls can lead to all sorts of weird behavior in your application. Especially when they are hosted in forms that are loaded and unloaded during the lifetime of your application.

public partial class FlexiAddress : UserControl
{
    public static event EventHandler<AddressChangedEventArgs> EventAddressChanged; 

The danger here is that unless you unhook from the static event before your form closes what happens is that although the form is not visible it still hangs around in memory until your application exits.

So if you are showing the form by creating a new instance, every form that is created is loaded into memory and will actually cause a memory leak.

If you want to prove this to yourself the easiest way is to include a Debug.WriteLine in the even handler and then after you've opened and closed the hosting form a couple of times try to do an action that causes the event to be fired. You'll notice that the Output window has one line for each instance of the form that is loaded in memory.

The solution, is to remove the hook to the event handler, the Form_Closing event is probably a good place to include this.

AddressControl.EventAddressChanged -= AddressControl_EventAddressChanged;

The better solution though is to avoid using static events.

Categories:

Updated: