When do I have to unsubscribe from events?

3

A question on the same theme has a answer it says:

  

You do not have to unsubscribe from an event when the instance that is subscribing has the same scope as the instance that is being subscribed to.

Free translation:

  

You do not need to "unsubscribe" from an event when the subscribed object and the subscriber object have the same lifetime.

     

Ex: Object A (subscriber) creates object B (subscript), A subscribes an event of B.

As for this I have no doubt. This is the most frequent situation when using events.
My problem is to identify a situation other than that.

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

    
asked by anonymous 10.10.2014 / 16:23

1 answer

3

Contrary to answer is the scenario in which you will be it is necessary to cancel the subscription, ie when the lifetimes 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 the objects is clearly different. Therefore, it is necessary to cancel the event signature when the instantiated object is no longer necessary, otherwise the static event, as it contains a reference to the instantiated object, will prevent it from being collected by GC .

    
23.10.2014 / 20:56