Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Know how many EventHandlers are set?

As we all know, we can create an EventHandler and add methods to it N number of times. Like:

   // Declare and EventHandler     
   public event EventHandler InternetConnectionAvailableEvent;
    private void OnInternetConnectionAvailableEvent()
    {
        if (InternetConnectionAvailableEvent != null)
        {
            EventHandler handle = InternetConnectionAvailableEvent;

            EventArgs e = EventArgs.Empty;
            handle(this, e);
        }
    }


   // IN OTHER CLASS WHERE I USE THE EVENT
   // Set the method name to handle the event    
   monitorInternet.InternetConnectionAvailableEvent += HandleInternetConnectionEvent;

    void HandleInternetConnectionEvent(object sender, EventArgs e)
    {
        if (syncContext != null)
        {
            MonitorInternetConnection mic = (MonitorInternetConnection)sender;
            if (mic != null)
            {
                syncContext.Post(o => InternetConnected(), null);
            }
        }
    }

   // To remove
   monitorInternet.InternetConnectionAvailableEvent -= null; 

UPDATE :

   // To remove it should be 
   monitorInternet.InternetConnectionAvailableEvent -= HandleInternetConnectionEvent;  // CORRECT

Same method can be called multiple times without removing it.

If I make monitorInternet.InternetConnectionAvailableEvent -= null;, all the event handlers be removed. I mean if it is set 2-3 times, and removed only once, by making it null, also all the other methods will be removed automatically.

I believe it will, but I just wanted to confirm with you experts. While googling I didn't get my required satisfactory answer.

Please correct me if am wrong.

like image 732
Tvd Avatar asked Jun 22 '11 12:06

Tvd


2 Answers

To find the number of event handlers, you can use this code:

InternetConnectionAvailableEvent.GetInvocationList().Length;

The following code demonstrates that MyEvent -= null does not clear the list of handlers.

public static event EventHandler MyEvent;

[STAThread]
static void Main()
{
   MyEvent += (s,dea) => 1.ToString();
   MyEvent -= null;

   Console.WriteLine(MyEvent.GetInvocationList().Length);
   // Prints 1
   MyEvent = null;
   Console.WriteLine(MyEvent == null);
   // Prints true
}

To clear the list (which is probably never a good idea), you can set the event to null (as long as you are in the class that declared the event).

like image 159
agent-j Avatar answered Oct 14 '22 07:10

agent-j


Delegates are removed by equality, so you're not removing anything from the invocation list because nothing in the invocation list would be null.

like image 44
Grant Thomas Avatar answered Oct 14 '22 07:10

Grant Thomas