If we define a delegate:
public delegate void Callback (string s);
And if the publisher class contains an event:
public event Callback Notify;
Then the subscriber’s constructor will contain the registration code, and his class will contain the “Update” method, which will subscribe to the event:
class Subscriber { Publisher publisher; public Subscriber (Publisher publisher) { this.publisher = publisher; publisher.Notify += Update; } public void Update(string subjectState) { state = subjectState; } }
To change this subscriber to unregister from the event when he is about to die, we need to implement Finalizer for his class:
~Subscriber () { if (publisher != null) { publisher.Notify -= Update; } }
Thus, we can be sure that the subscriber will no longer be registered in the event. for more information on the Finalize method, read this great MSDN garbage collection article.
source share