Check if event has any listeners?
Is i开发者_开发知识库t possible to detect if event has any listeners? (I need to dispose my event provider object, if nobody needs it)
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
}
You can check if event is != null.
By the way, in C# you need this check each time you raise an event:
if (TheEvent != null) {
TheEvent(this, e);
}
and the reason is exactly to check if the event has any listener.
EDIT
Since you can't access TheEvent from outside the class, you could implement a method that does the check:
public class TheClass {
public bool HasEventListeners() {
return TheEvent != null;
}
}
void Main()
{
Console.WriteLine(ContainsOnSomethingEvent()); // false
OnSomething += (o,e) => {};
Console.WriteLine(ContainsOnSomethingEvent()); // true
}
EventHandler mOnSomething;
event EventHandler OnSomething {
add { mOnSomething = (EventHandler)EventHandler.Combine(mOnSomething, value); }
remove { mOnSomething = (EventHandler)EventHandler.Remove(mOnSomething, value); }
}
public bool ContainsOnSomethingEvent() {
return mOnSomething != null && mOnSomething.GetInvocationList().Length > 0;
}
精彩评论