Garbage collector and event handlers

后端 未结 2 1004
無奈伤痛
無奈伤痛 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.

提交回复
热议问题