Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing anonymous event handler

Tags:

c#

wcf

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?

like image 304
Jason Quinn Avatar asked Nov 29 '10 12:11

Jason Quinn


People also ask

Can you remove event listener with anonymous function?

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job.

Can event handlers be removed?

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.

How do I remove an event listener?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.


1 Answers

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.

like image 99
Tim Robinson Avatar answered Oct 01 '22 12:10

Tim Robinson