There are basically two patterns in avoiding duplicated registering of event handlers: (According to this discussion: C# pattern to prevent an event handler hooked twice)
Using System.Linq namespace, and check if the event handler is registered by calling GetInvocationList().Contains(MyEventHandlerMethod);
Do the unregistering before registering, like this:
MyEvent -= MyEventHandlerMethod;
MyEvent += MyEventHandlerMethod;
My question is, performance-wise, which one is better, or is there a significant difference between them in performance?
I don't think this matters a lot, both in assumed performance gain and actual difference.
Both GetInvocationList
and -=
walk the internal array _invocationList
. (See source)
The LINQ extension method Contains
will take more time since it needs the entire array to be walked and converted, returned and then checked by Contains
itself. The Contains
has the advantage it doesn't need to add the event handler if it exists which will mean some performance gain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With