开发者

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

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 开发者_StackOverflowEventHandler(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?


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.


It will in C# - I don't know about Java. You are adding multiple delegates to the same method and each one will get called in turn.

Here is a quick example that proves it:

using System;

class Example
{
    static event Action Bar;

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

        Bar();
    }

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


Duplicates are allowed in invocation list, so yes, the method will be executed several times. In C# at least.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜