0
public Messenger(Socket socket, string username)
    {
        sock = socket;
        controller = new SocketHandler.Controller(socket);
        controller.onReceiveData += ParseMessage;
        controller.onCloseConnection += OnCloseConnection;
    }

...

if (game == Messenger.GAME_TOKEN)
        {
            new Messenger(socket, username);
        }

I don't want to have to manage some reference to the new instance of the Messenger class that I create. Will the reference to the private method that I add to the onCloseConnection Action in the controller suffice to keep the Messenger instance from being garbage collected?

I could always be on the safe side and manage it but the simpler the better.

John Saunders
  • 160,644
  • 26
  • 247
  • 397

1 Answers1

0

I re-read your question, and I think that the reference to the OnCloseConnection method of Messenger will keep the Messenger instance alive.

DWright
  • 9,258
  • 4
  • 36
  • 53
  • What if the method returned it's own instance? Then it could be reached through Controller – Jeremy Gagnier Apr 15 '15 at 02:38
  • Not sure I followed that. – DWright Apr 15 '15 at 02:39
  • Accidentally put messenger instead of controller. So the Messenger creates the Controller in its constructor and gives the Controller a reference to one of its methods. Say the method returns the instance of the Messenger. Then it is reachable from the Controller, and thus possibly reachable by anything else. – Jeremy Gagnier Apr 15 '15 at 02:42
  • I think I was wrong. I re-read your original post and now I think that if OnCloseConnection is a Messenger method as you seem to indicate, it'll keep the Messenger alive. – DWright Apr 15 '15 at 02:46
  • From the context, it's pretty clear that the method is an instance method. If it were a static method, it would not keep it alive. – DWright Apr 15 '15 at 02:50
  • Wow thanks, guess I didn't use the right words in my google search. – Jeremy Gagnier Apr 15 '15 at 02:53