Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an event gets executed twice if callback was assigned twice to the object?

Tags:

java

c#

I have a code that attaches an event to a form.

this.form.Resize += new EventHandler(form_Resize);

As you see this is done by +=. If the above code is executed twice or multiple times,

like this:

this.form.Resize += new EventHandler(form_Resize);
this.form.Resize += new EventHandler(form_Resize);
this.form.Resize += new EventHandler(form_Resize);
this.form.Resize += new EventHandler(form_Resize);
this.form.Resize += new EventHandler(form_Resize);

Is the callback method attached multiple times?

How many times will be called the method form_Resize ?

Does an event gets executed multiple times if it's callback method was assigned multiple times to the same object?

like image 800
Pentium10 Avatar asked Feb 27 '23 14:02

Pentium10


1 Answers

The event handler will get called once for each time it is attached. (C#)

To guard against double attachment you can use this pattern:

this.form.Resize -= new EventHandler(form_Resize); 
this.form.Resize += new EventHandler(form_Resize); 

The first statement will not throw an error if there are no handlers attached and will remove an existing handler.

like image 57
Doug Ferguson Avatar answered Apr 28 '23 06:04

Doug Ferguson