Qn: Adding and removing event delegates

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all

If I add multiple references to the SAME delegate in an event object..
How many references are stored in the delegate list managed by the object.

eg.

if I ..

SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;

And then

SomeObject.SomeEvent -= TotherObject.SomeEventHandler;

Will SomeObject.SomeEvent contain a reference to TotherObject.SomeEventHandler

// On a second note, Sorry I know this is not the place

Can someone point me to the *best* WinCE newsgroup focused on C++ dev for
user mode apps using eVC++?

Cheers

Steve
 
Hi Steve,
How many references are stored in the delegate list managed by the object.
eg.
if I ..
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
SomeObject.SomeEvent += TotherObject.SomeEventHandler;
Five. When invoking the even, the five methods will in invoked in the
order you added them.
And then
SomeObject.SomeEvent -= TotherObject.SomeEventHandler;
Will SomeObject.SomeEvent contain a reference to >TotherObject.SomeEventHandler
The last TotherObject.SomeEventHandler will be remove. You still have
four!

Regards,
Thi
 
Thanks Truong,

IMHO it's a pity that an event calls the same delegate multiple times. It
would be nice if the delegate was only added once to the list managed by the
event object.

Regards

Steve
 
steve said:
Thanks Truong,

IMHO it's a pity that an event calls the same delegate multiple times. It
would be nice if the delegate was only added once to the list managed by
the
event object.

Regards

Steve

You can achieve this behavior yourself by overriding the event registration
and unregistration and only adding a particular target once.

private EventHandler myEvt;
public event EventHandler MyEvt
{
add
{
if( myEvt != null )
{
bool found = false;
foreach( EventHandler evt in myEvt )
{
if( evt.Equals(value) )
{
found = true;
break;
}
}
if( !found )
{
myEvt += value;
}
}
}
remove
{
myEvt -= value;
}
}

Caveat: I wrote the code in Outlook Express - but it should give you the
general idea.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk?
 
Back
Top