Delegates Problem - calling method more time then expected

Hi all,

I am having very strange problem. I am using delgate to call one of the method in the class. The problem is eveytime the event occurs it increasing the call value by one. For example when first time the event occurs it calls the method once, than second time twice and so on. I checked my code to find if there are any multiple copies of the same object lying around and didn't find any. Here is the code i am using.

site.SocketChanged += new AC.Site.SocketEventHandler(site_SocketChanged); // where site is the object of type Site

void site_SocketChanged(AC.Site site)

{

object[] param = new object[] { site };

AC.SafeInvokeHelper.Invoke(this, "UpdateSite", param);

}

in the class Site I have following code.

public delegate void SocketEventHandler(Site site);

public virtual event SocketEventHandler SocketChanged;

//when event occurs

this.SocketChanged.Invoke(this);

I don't think there is anything wrong with the code. When I debug i can see that it actually calls site_SocketChanged more than once. Any suggestions are appreciated. Thanks in advance

Rushi



Answer this question

Delegates Problem - calling method more time then expected

  • gift

    Thanks to both of you for replying and solving my problem. I was actually attching multiple events to the site object by executing "site.SocketChanged += new SocketEventHandler (... )" more than once. I think it's been sorted now. Thanks a lot

    Rushi


  • Gary Cabana

    In some way the line

    site.SocketChanged += new AC.Site.SocketEventHandler(site_SocketChanged); // where site is the object of type Site

    must be executed multiple times in your code. You can set a breakpoint to verfiy this.

    This code actually adds a listener to the event's listener collection, which is enumerated when firing the event. If someone has registered more than once, the event will be delivered more than once (as you can expect).


  • Secrets

    How many times is this line executed :

    site.SocketChanged += new SocketEventHandler (... )



    You can attach multiple event-handlers to an event (multi-cast events). So, if that line of code is executed twice, your event will have 2 event-handlers (2 times the same method).
    If you execute that line another time, you'll have 3 event-handlers, so, that method will be executed 3 times, etc....




  • Delegates Problem - calling method more time then expected