6

If I have the classic ways to register and unregister events (+= -=), is there also a way to see whether something is registered right now?

Let's say I have 2 methods which can register on one Timer. If something has already registered at .Elapsed, I do not want anything else to register (and do not want something to register multiple times).

Is there any way to look up which methods are registered at the moment to a specific event?

3
  • 1
    Do you mean at runtime? or at coding time?
    – Steve B
    Commented Jan 14, 2013 at 14:34
  • 3
    See: stackoverflow.com/questions/136975/…
    – Dejo
    Commented Jan 14, 2013 at 14:41
  • At runtime from outside of the Timer class. @dejo thanks, have not used the correct search phrase, therefore did not found that post. But still curious if it also works with a type of extension method (like joel's post below)
    – Offler
    Commented Jan 14, 2013 at 15:35

2 Answers 2

5

If you really want such behaviour, I think the best option is to use the overload the add{} and remove{} functionality of the event.

public class Foo
{

   private EventHandler<ElapsedEventArgs> _elapsed;

   public EventHandler<ElapsedEventArgs> Elapsed
   {
       add
       {
           if( _elapsed == null )
               _elapsed += value;
           else
               throw new InvalidOperationException ("There is already an eventhandler attached to the Elapsed event.");
       }
       remove
       {
           _elapsed -= value;
       }
   }

}
2
  • 4
    Yes, but turning it into a NOP is disputable. Throwing might be more appropriate. Commented Jan 14, 2013 at 14:49
  • It's a solution together with GetInvocationList() for me.
    – Offler
    Commented Jan 18, 2013 at 6:47
1

You can use GetInvocationList() and get the count in turn

Not the answer you're looking for? Browse other questions tagged or ask your own question.