How to check membership of an event handler from outside the owning class?

This question asks if there is a way to find if the code has already added its own event handler to an event. However, the answers given only work from inside the same class that own the event. (Delegate.GetInvocationList and others.)

I want to add a custom event handler to AppDomain.CurrentDomain.AssemblyResolve. Is there a way to find out if my custom handler is already added before adding it again? (For this and other standard library events.)

If the answer is indeed "That's impossible." then please give that as an answer.

Jon Skeet
people
quotationmark

That's impossible.

Basically, the only operations you have with an event from the outside are "subscribe" and "unsubscribe".

Now you could always unsubscribe before you subscribe. Unsubscribing is a no-op if the specified handler isn't already a handler for the event. If you make sure you always do that, then you'll definitely have exactly one handler subscribed. It does mean you need to be careful to do that everywhere you subscribe though - so ideally, put that code in one place.

(Alternatively, just change your event subscription so that you can easily tell that you'll only ever subscribe once...)

people

See more on this question at Stackoverflow