Why three times get called?

T

TJ

Hi,

Below is my testing event hadnlder code.

interface IEventTest
{
void Call();
event EventHandler OnEventHandler;
}

public class EventTest : IEventTest {

public EventTest()
{
}

public void Call()
{
if (eventHandler != null)
{
eventHandler(this, new EventArgs());
}
}

event EventHandler eventHandler;
event EventHandler IEventTest.OnEventHandler
{
add
{
if (eventHandler != null)
{
lock (eventHandler)
{
eventHandler += value;
}
}
else
{
eventHandler = new EventHandler(value);
}
}
remove
{
if (eventHandler != null)
{
lock (eventHandler)
{
eventHandler -= value;
}
}
}
}
}

This is my testing code.

private void button3_Click(object sender, EventArgs e)
{
IEventTest et = new EventTest();
et.OnEventHandler += new EventHandler(et_OnEventHandler);
et.Call();
et.OnEventHandler -= new EventHandler(et_OnEventHandler);

et.OnEventHandler += new EventHandler(et_OnEventHandler);
et.Call();
et.OnEventHandler -= new EventHandler(et_OnEventHandler);

}

void et_OnEventHandler(object sender, EventArgs e)
{
MessageBox.Show("Called");
}

I think messagebox should be displayed two times...not three times..
Why the messagebox is showing three times?
As U see the code, I removed the event handler before calling next Call
method.

Thanks,
 
J

Jeff Johnson

[Canned response]
You have posted this question individually to multiple groups. This is
called Multiposting and it's BAD. Replies made in one group will not be
visible in the other groups, which may cause multiple people to respond to
your question with the same answer because they didn't know someone else had
already done it. This is a waste of time.

If you MUST post your message to multiple groups, post a single message and
select all the groups (or type their names manually, separated by commas) in
which you want it to be seen. This is called Crossposting and when used
properly it is GOOD.

Your question has been answered in another group. Which one? See the problem
with multiposting?

(This isn't just my opinion. Look here:
http://www.oakroadsystems.com/genl/unice.htm#xpost)
 

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