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?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Offler
  • 1,223
  • 1
  • 12
  • 34
  • 1
    Do you mean at runtime? or at coding time? – Steve B Jan 14 '13 at 14:34
  • 3
    See: http://stackoverflow.com/questions/136975/has-an-event-handler-already-been-added – Dejo Jan 14 '13 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 Jan 14 '13 at 15:35

2 Answers2

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;
       }
   }

}
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
1

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

Nasmi Sabeer
  • 1,370
  • 9
  • 21