I have the following code where SprintServiceClient is a reference to a WCF Service-
public class OnlineService { private SprintServiceClient _client; public OnlineService() { _client = new SprintServiceClient(); } public void AddMemberToTeam(MemberModel user, int projectId, Action<int> callback) { _client.AddMemberToTeamCompleted += (s, e) => callback(e.Result); _client.AddMemberToTeamAsync(user.ToUser(), projectId); } }
the problem is that every time AddMemberToTeam is called it adds another callback to client.AddMemberToTeamCompleted
i.e the first time AddMemberToTeam is called the callback is called once, the second time AddMemberToTeam is called the callback is called twice ect.
Is there any way to remove the eventhandler from AddMemberToTeamCompleted once the eventhandler has been called or use another method which takes in the callback?
This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job.
Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
You can refer to your anonymous method from inside itself as long as you assign a delegate to a variable first:
EventHandler<SomeEventArgs> handler = null; handler = (s, e) => { _client.AddMemberToTeamCompleted -= handler; callback(e.Result); }; _client.AddMemberToTeamCompleted += handler;
Note that you need to declare the variable and assign it separately or the compiler will deem it uninitialized when you come to use it inside the method body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With