I still have some doubts as I have never seen such a design pattern in any .NET library
Yes, you are right to worry about it. These types of event subscriptions are very inconsistent, the event source always allocates a subscriber. There is only one class within the framework that I know does this, SystemEvents. The problem is that each subscriber must very carefully unsubscribe when his life ends, or the object will constantly refer to him. A memory leak that is very difficult to diagnose.
It is best to use an interface. Let one declare:
public class MyEventArgs { } public interface IGlobalNotification { event EventHandler Disposed; void OnMessage(MyEventArgs arg); }
Now you have the opportunity to implement the interface interface:
public partial class Form1 : Form, IGlobalNotification { public Form1() { InitializeComponent(); GlobalMessages.Register(this); } void IGlobalNotification.OnMessage(MyEventArgs arg) {
The Register method registers the form with the GlobalMessages class, the Dispose event ensures that the class can detect that the form is dying:
public static class GlobalMessages { public static void Register(IGlobalNotification listener) { listener.Disposed += delegate { listeners.Remove(listener); }; listeners.Add(listener); } public static void Notify(MyEventArgs arg) { foreach (var listener in listeners) listener.OnMessage(arg); } private static List<IGlobalNotification> listeners = new List<IGlobalNotification>(); }
Call GlobalMessages.Notify () to run the OnMessage () method on all instances of the live form. The main advantage of this approach is that the client programmer can never mess up.
source share