By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,824 Members | 1,252 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,824 IT Pros & Developers. It's quick & easy.

Event and Event Handlers.

P: n/a
I'm trying to figure out if there is any way to determine if a class
has already registered as a handler for an event. Let's say I've got a
class Emitter that has an event
EmitterEvent
and a delegate
void EmitterEventHandler(Emitter sender)

I've got another class Listener that wants to listen for the
EmitterEvent. So I do the following:
emitter.EmitterEvent += new EmitterEventHandler(emitter_EmitterEvent);

This, of course works, and if I do it twice:
emitter.EmitterEvent += new EmitterEventHandler(emitter_EmitterEvent);
emitter.EmitterEvent += new EmitterEventHandler(emitter_EmitterEvent);

I recieve the event twice. I want to avoid that, so before registering
the EmitterEventHandler, I'd like to check if I'm already registered
for it. Something like this:

emitter.EmitterEvent.EmitterEvent.GetInvocationLis t().Contains(new
EmitterEventHandler(emitter_EmitterEvent);

Which is not possible.

Is there any way to do this? My current solution is to make the
EmitterEvents private and the following methods to my Emitter class:
public void RegisterHandler(EmitterEventHandler h)
{
//if EmitterEvent is null, just attach the Handler
if(this.EmitterEvent==null)
{
this.EmitterEvent+=h;
}
else
{
bool contains = false;
Delegate[] dels = EmitterEvent.GetInvocationList();
foreach(Delegate d in dels)
{
if(d == h)
{
contains = true;
break;
}
}
if(!contains)
{
this.EmitterEvent+=h;
}
}
}
and
public void UnRegisterHandler(EmitterEventHandler h)
{
this.EmitterEvent-=h;
}

This works, but isn't that pretty. Any better solutions?

Feb 9 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
How about

emitter.EmitterEvent -= new EmitterEventHandler(emitter_EmitterEvent);
emitter.EmitterEvent += new EmitterEventHandler(emitter_EmitterEvent);

The first line will have no effect if the class has not already
subscribed to the event. The second line will always add the handler.
So, no matter what the situation, you always end up with the handler
exactly once on the event chain.

Feb 9 '06 #2

P: n/a
You're right. I was making this FAR to complicated. Although I think
I'm going to keep with the register/unregister idea. It seems a bit
cleaner.

Feb 10 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.