Do I need to unsubscribe events in my Form?

前端 未结 4 736
不知归路
不知归路 2020-12-19 17:23

I\'m trying to understand how a Control events are unsubscribed. Suppose I have a textbox and I have subscribed the TextChanged event using the Win

4条回答
  •  忘掉有多难
    2020-12-19 17:31

    In this situation I beleive it is OK not to unsubscribe because the TextBox to which you're subscribing is wholly contained within the parent control (or that's what I'm assuming.)

    Therefore when no further references to the parent control exist, there won't be any external references to the TextBox and so both objects will become eligible for GC.

    There are situations when you should unsubscribe from events to prevent memory leaks because the reference held by the event (in it's list of subscribers) is just the same as any other reference and would prevent the subscriber from being GC'd.

    Such situations can occur when an object subscribes to an event on an external object (i.e. not owned by this object.) In this situation the subscriber would only become eligible for GC after the subscribed-to object was eligible for GC.

提交回复
热议问题