Is there a memory leak if I pass the control to another class to handle events?

Considering that the mentioned class and subscribes to control events AND refers to the control.

Background: I have custom scrollbars on multiple forms / usercontrols and decided to extract the scrollable code into a class named "ScrollLogic" so that it can be reused. The class constructor looks like this:

Sub New (bntUp as Button, bntDown as Button, panelToScroll as Panel, _
         scrollLength As Integer)

        Me.bntUp = bntUp         'Declaration: Private bntUp As Button     
        AddHandler Me.bntUp.Click, AddressOf UpClicked

       'Setup code for other controls/variables here  

End Sub

      

When the button is clicked, the ScrollLogic will scroll the ToScroll pane using the AutoScrollPosition property. If the scroll limit is reached, the corresponding button will be invisible. (or visible if scrolls in the opposite direction become possible after scrolling)

It works great, but I noticed that

  • ScorllLogic subscribes to button click events to work

  • ScrollLogic contains links to buttons to control their visibility. It is not enough to have access to the event sender as bntUp must be set visible when the bntDown button is pressed .

Is it leaking memory? I am trying to avoid overriding dispose () of all forms / usercontrols that have been affected by ScrollLogic objects, because that would be ugly. Any suggestion would be appreciated, thanks

+3


source to share


1 answer


No, there is no leak here. Subscribing to button events (buttons) creates a link from the button to the class object, and not vice versa. Target chain: form => buttons => your object. Thus, everyone is entitled to collection as soon as the user closes the form or you destroy it.

Even if your class contained a link to buttons (none are visible), then it still doesn't matter, GC has no problems with circular references.



There is no clue where you store the reference to your class object. Of course nowhere, no one needs it as the buttons are good enough to keep it going. It is very difficult to confuse this, you have to do something drastic like storing it in a static variable. Get a feel for this by writing a little test code that creates / shows / expands a form thousands of times.

+4


source







All Articles