Search code examples
c#.netwebmethod

EventArgs has always the same value when trying to pass parameters to event handler


I want to pass parameters to the event handler of a web method. I added an auto-unsubscription logic to avoid that the event handler gets fired multiple times. The problem is that I always get the same instance of the EventArgs object in the event handling method.

ie: If I call GetInfo 3 times with 3 different values for infoVersion, the event handling function gets fired 3 times but I will always get the same instance of the variable e.

public void GetInfo(int infoVersion)
{
      System.EventHandler<ServiceReference.getInfoCompletedEventArgs> handler = null;
        handler = (sender, e) =>
        {
            client.getInfoCompleted -= handler;
            client_getInfoCompleted(sender, e, infoVersion);
        };

        client.getInfoCompleted += handler;
        client.getInfoAsync(infoVersion);

}

void client_getInfoCompleted(object sender, ServiceReference.getInfoCompletedEventArgs e, int infoVersion)
{
    //do something with e.result and infoVersion
    //e.result is always the same but infoVersion is correct
}

EDIT: The web method has been tested and works fine. The e.result shall change if I modify the infoVersion value.

If I use a more simple approach like below, e.result will be different each time:

public void GetInfo(int infoVersion)
{
    client.getInfoCompleted += client_getInfoCompleted;
    client.getInfoAsync(infoVersion);
}

void client_getInfoCompleted(object sender, ServiceReference.getInfoCompletedEventArgs e)
{
   //e.result has a different value each time.
}

Solution

  • Haha thats a cute one. The first event that fires calls the handler for all 3 calls and removes their event registration, which makes the other ones not arrive.

    To solve this, you can create a client for each call so the events won't intersect with each other.

    A better solution would be using an async API that will recieve a callback for each call. If this is an automatically generated proxy class you can make it generate these kinds of methods.

    Note: This requires .Net 4.5

    enter image description here