My class has an event which external objects will subscribe to:
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
However, an internal Listener object, running on it's own thread, will actually be originating the event.
private class Listener
{
public void Run()
{
// events raised here which should be forwarded
// to parent's MessageReceived
}
};
My inclination is to create an event with the same signature on the Listener, and subscribe to it in the main class in order to raise it on MessageReceived. This seems a little cumbersome, so I was wondering if there is a neat/idiomatic way of forwarding events like this.
You can use event add/remove accessors so that events wired to the external-facing event are "forwarded" to the internal listener
public event EventHandler<MessageReceivedEventArgs> MessageReceived {
add { this.listener.MessageRecieved += value; }
remove { this.listener.MessageRecieved -= value; }
}
This means you need to create an event in the listener, but the benefit is that there is no other plumbing to wire up the event.
You could do that with an event, or you could create a method in your main class called ReceiveMessage() and call that from the listener (and then raise the event from there).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With