Removing anonymous event handler

后端 未结 3 2046
半阙折子戏
半阙折子戏 2021-01-03 19:57

I have the following code where SprintServiceClient is a reference to a WCF Service-

public class OnlineService
{
    private SprintServiceClient _client;
           


        
3条回答
  •  余生分开走
    2021-01-03 20:24

    The trick to making a self-unsubscribing event-handler is to capture the handler itself so you can use it in a -=. There is a problem of declaration and definite assignment, though; so we can't do something like:

    EventHandler handler = (s, e) => {
        callback(e.Result);
        _client.AddMemberToTeamCompleted -= handler; // <===== not yet defined     
    };
    

    So instead we initialize to null first, so the declaration is before the usage, and it has a known value (null) before first used:

    EventHandler handler = null;
    handler = (s, e) => {
        callback(e.Result);
        _client.AddMemberToTeamCompleted -= handler;        
    };
    _client.AddMemberToTeamCompleted += handler;
    

提交回复
热议问题