Event and Event Handlers.

  • Thread starter 00unknown.user00
  • Start date
0

00unknown.user00

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.GetInvocationList().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?
 
B

Bruce Wood

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.
 
0

00unknown.user00

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top