WCF Completed Event firing more than once

The problem situation is stated in the title. =P

The “fix” to the problem is something real simple. I didn’t notice it when it happened to me the first time. This post is also posted to remind myself about it.

This is an example of a code with the problem.

public class WorkingArea{
Server.ServiceClient client = new Server.ServiceClient();

public WorkingArea()
{
InitializeComponent();
}

private void btnCheck_Click(object sender, RoutedEventArgs e)
{
client.CheckCompleted += new EventHandler(Client_UpdateCompleted);
client.CheckAsync(Value);
}
}

This code seems to be working fine. I have a Service which I declare it as client and everytime I click on the button Check, i attach the event handler and call the async method to run it. But wait, what went wrong is this.
“…..everytime I click on the button Check, i attach the event handler and call…….”

What happen is there will be alot handlers being attached to the client variable as times go by ( with the user clicking the button in our example ). The callback/comepleted event will increasingly happen with the button click in this example. With abit of moving of that line where you attach the handler. This will solve the problem.
“client.CheckCompleted += new EventHandler(Client_UpdateCompleted);”

I will recommend putting this in the constructor, loaded event handler or onNaviagtedTo. This will depends on what is the architecture of the application you are building.

If you have any question, please feel free to contact me at guohong@limguohong.com or use the contact page. Please visit the tutorials page for more tutorials from Microsoft Office to Windows Phone!