Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if event has any listeners?

Tags:

c#

.net

clr

Is it possible to detect if event has any listeners? (I need to dispose my event provider object, if nobody needs it)

like image 489
user626528 Avatar asked Jun 09 '11 10:06

user626528


People also ask

How do you check if there is an event listener exists?

To check whether dynamically attached event listener exists or not with JavaScript, we can get and set the element's listener attribute. export const attachEvent = ( element: Element, eventName: string, callback: () => void ) => { if (element && eventName && element. getAttribute("listener") !== "true") { element.

How do I check if an element has a click event?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

How do I remove all event listeners?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.


1 Answers

Assume the class is in a 3rd party library and it can't be modified:

    public class Data
    {
       public event EventHandler OnSave;
       //other members
    }

In your program:

    Data d = new Data();
    d.OnSave += delegate { Console.WriteLine("event"); };
    var handler = typeof(Data).GetField("OnSave", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(d) as Delegate;

    if (handler == null)
    {
        //no subscribers
    }
    else
    {
        var subscribers = handler.GetInvocationList();
        //now you have the subscribers
    }
like image 112
Cheng Chen Avatar answered Sep 23 '22 13:09

Cheng Chen