How to implement events that are unsubscribed when the subscriber no longer refers?

I am trying to implement a messaging system, and I just used the usual .NET events, but the problem was that the publisher lives longer than the subscriber, and the publisher refers to the subscriber and prevents an unregistered event.

I was looking for weak events, but there were a lot of them, and I had problems with deception around me. I want something simple.

In addition, most of them do not immediately unregister an event when it does not contain links. I would like the system to immediately unregister the event after the object had no more links or went out of scope.

I'm fine by not using the syntax sugar built-in events and instead use the public static class to ease all the effort.

I would just like to raise an event in one class, which will call the methods of all subscribers, which would automatically cancel the registration immediately after the subscriber is no longer used.

Can this be done or does it already exist in the structure in some way?

+4
source share
1 answer

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.

0
source

Source: https://habr.com/ru/post/1446817/


All Articles