When do I have to unsubscribe (unsubscribe) events?

Asked

Viewed 78 times

3

One question on the same subject has a reply what it says:

You don’t have to desubscribe from an Event when the instance that is subscribing has the same Scope as the instance that is being subscribed to.

Free translation:

It’s not necessary "unsubscribe" of an event when the subscribed object and the subscribing object have the same life span.

Ex: Object A(subscriber) creates object B(subscribed), A subscribes to an event B.

I have no doubt about this. It is the most frequent situation when using events.
My difficulty is in identifying a situation other than this.

What I ask is an example/explanation of when the "unsubscribe" of events is required.

1 answer

3


The opposite of reply is the scenario in which it will be necessary to cancel the subscription, that is, when the life times of the objects are different.

Take the example of a static event:

public static class MyStaticClass
{
    public static event OnMyEvent MyEvent;
}

And an instance that subscribes to this event:

public class MyClass
{
    public MyClass
    {
        MyStaticClass.MyEvent += ...
    }
}

In this case, the lifetime of objects is clearly different. Thus it is necessary to cancel the event signature when the instantiated object is no longer necessary, otherwise the static event, as they contain a reference to the instantiated object, will prevent it from being collected by the GC.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.