Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forwarding/relaying .NET events

Tags:

c#

.net

events

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.

like image 784
marijne Avatar asked Jun 01 '09 14:06

marijne


2 Answers

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.

like image 153
Ryan Emerle Avatar answered Oct 24 '22 18:10

Ryan Emerle


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).

like image 30
Jon B Avatar answered Oct 24 '22 17:10

Jon B