.NET Event Forwarding / Relaying

In my class there is an event to which external objects will be attached:

public event EventHandler<MessageReceivedEventArgs> MessageReceived; 

However, an internal Listener that runs on its own thread will actually trigger an event.

 private class Listener { public void Run() { // events raised here which should be forwarded // to parent MessageReceived } }; 

My tendency 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 to MessageReceived. This seems a bit cumbersome, so I was wondering if there is a neat / idiomatic way to forward such events.

+7
c # events
source share
3 answers

You can use the add / remove accessors event so that events associated with an external event are "redirected" to the internal listener

 public event EventHandler<MessageReceivedEventArgs> MessageReceived { add { this.listener.MessageRecieved += value; } remove { this.listener.MessageRecieved -= value; } } 

This means that you need to create an event in the listener, but the advantage is that there is no other plumbing to connect the event.

+22
source share

You can do this with an event, or create a method in your main class called ReceiveMessage () and call it from a listener (and then raise the event from there).

+1
source share

As already mentioned, you can create custom subscription logic by adding and removing handlers at your event.

Please note that this design has a problem as is. You indicate that your listener is raising an event in its thread. By default, handlers will be called on the thread that raised the event (in your case, the Listener thread). You have several options.

  • If you are not interested in the Listener thread making callbacks. Just call the event as it is (but the Listener thread may be blocked if the event handler takes some time to execute or just die if the event handler throws an unhandled exception)
  • If you want the handlers to be executed in threads other than the Listener thread, but do not care about which threads until it is in the listener: in the OnXXX method, which actually calls the handlers, get a list of event calls and queues of each handler in threadpool.
  • If you want handlers to be called on certain threads: a little complicated, you need to use some SynchronizationContext (WindowsSynchronizationContext in Winforms, custom in other cases, etc.).

There, the blog post by Roy Osherove shows several ways to make asynchronous calls: http://weblogs.asp.net/rosherove/pages/DefensiveEventPublishing.aspx (but I would not use asynchronous delegate calls and instead relied directly on ThreadPool to call delegates) .

+1
source share

All Articles