Garbage collector and event handlers

后端 未结 2 988
無奈伤痛
無奈伤痛 2021-01-02 11:44

A quick question. Say that I have a class implemented as in below example.

class Subscriber
{
    private Publisher publisher = new Publisher;


    public S         


        
相关标签:
2条回答
  • 2021-01-02 11:56

    If during the GC lifetime of an event publisher, an arbitrarily large number of event subscribers may be brought into existence and abandoned without being unsubscribed, such dangling subscriptions will constitute a memory leak. If the event publisher will become eligible for garbage collection around the time the subscribers are abandoned or, at worst, there is for each publisher a bounded number of subscribers that may be created and abandoned, there is no memory leak.

    One of my peeves with .net is that Microsoft does not facilitate event cleanup. This is particularly annoying in vb.net, which assures that changing a "WithEvents" variable will properly generate the proper subscriptions and unsubsriptions, but provides no convenient way for an IDisposable handler to unsubscribe all events held by an object.

    0 讨论(0)
  • 2021-01-02 12:08

    It wouldn't cause a leak - the GC can handle circular references with no problems.

    However, it would mean that the publisher would effectively have a reference to the subscriber, so the subscriber couldn't be garbage collected until either the publisher is eligible for GC, or it unsubscribes from the event.

    0 讨论(0)
提交回复
热议问题