C# pattern to prevent an event handler hooked twice

Ali Shafai picture Ali Shafai · Jun 2, 2009 · Viewed 92.2k times · Source

Duplicate of: How to ensure an event is only subscribed to once and Has an event handler already been added?

I have a singleton that provides some service and my classes hook into some events on it, sometimes a class is hooking twice to the event and then gets called twice. I'm looking for a classical way to prevent this from happening. somehow I need to check if I've already hooked to this event...

Answer

PrimeTSS picture PrimeTSS · Jul 9, 2009

How about just removing the event first with -= , if it is not found an exception is not thrown

/// -= Removes the event if it has been already added, this prevents multiple firing of the event
((System.Windows.Forms.WebBrowser)sender).Document.Click -= new System.Windows.Forms.HtmlElementEventHandler(testii);
((System.Windows.Forms.WebBrowser)sender).Document.Click += new System.Windows.Forms.HtmlElementEventHandler(testii);