Reputation: 363
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
}
}
Upvotes: 2
Views: 132
Reputation: 81513
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
Upvotes: 2