Search code examples
c#eventstcplistener

Subscribe to an event from an object created at run time


I have a Server class that creates a ClientHandler object at run time when a new connection is received. Inside ClientHandler I need to fire a clientEvent when specific messages are received. In my Form class I have a reference to the Server class but I need to subscribe to the clientEvent within ClientHandler object. However, the object doesn't exist yet at time of design. How can I do the subscription?

I created an event handler in Server that subscribes to the clientEvent, and it raises another serverEvent. In Form class I subscribe to the serverEvent. This way I'm listening to clientEvent indirectly. But I believe there's a better way to do this.

public delegate void SomeEvent(string message);

public class Server
{
  public ClientHandler clientHandler;
  public event SomeEvent serverEvent;
  // callback function when new connection received
  public void on_connected()
  {
    clientHandler = new ClientHandler(...)
    clientHandler.clientEvent += ClientEventHandler;
    }
  public void ClientEventHandler(string message)
  {
    serverEvent?.Invoke(message)
  }
}

public class ClientHandler
{
  public event SomeEvent clientEvent;
  // callback when message is read
  void ReadCallback(...)
  {
    ...
    // Some message received
    clientEvent?.Invoke("Message received: " + someMessage);
  }

public partial class From1 : Form
{
  public Form1()
  {
   Server server = new Server(...);
   server.serverEvent += serverEventHandler;
   ...
  }
  private void serverEventHandler(string message)
  {
   // do something with message
  }
}


Solution

  • There is nothing wrong with this approach, as long as you are sure to unsubscribe from the event when you remove your child.

    Here are the 3 main approach to this problem

    1. The Parent subscribes to the event of the child, Unsubscribing when the child is removed
    2. Passing a reference of parent to child, Calling the event on the parent when needed. This can be a little neater (sometimes) and more manageable.
    3. Using Decoupled Messaging through something like an Event Aggregator which will forward events from a publisher to a subscriber. They are decoupled because they need not know about each other and can skip the parent all together