Does the event fire twice if the callback has been assigned to the object twice?

I have code that attaches an event to a form.

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

As you can see, this is done using +=. If the above code is executed two or more 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 multiple times?

How many times will we call a method form_Resize?

Does the event fire several times if the callback method has been assigned several times to the same object?

+3
source share
3 answers

An event handler will be called once for each join. (WITH#)

To protect against double nesting, you can use this template:

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

, .

+6

# - Java. , .

, :

using System;

class Example
{
    static event Action Bar;

    static void Main()
    {
        Bar += Foo;
        Bar += Foo;

        Bar();
    }

    static void Foo()
    {
        Console.WriteLine("Foo");
    }
}
+2

, , . # .

0

Source: https://habr.com/ru/post/1732762/


All Articles