Do I need to unsubscribe events in my Form?

前端 未结 4 733
不知归路
不知归路 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:34

    The events are actually a list of event handlers (function delegates). So when you write this:

    this.emailTextBox.TextChanged += emailTextBox_TextChanged;
    

    You actually add your delegate emailTextBox_TextChanged to the list of existing delegates associated to the TextChanged event.

    What this means is that when the textbox is disposed, this list will be disposed too, so you don't need to unsubscribe events in that case, and you won't have memory leaks.

    So to answer your question, the event isn't really unsubscribed in the textbox destructor, but you don't need to do it explicitly.

    The only case in which it will be useful to unsubscribe is when you don't want your function to handle the event anymore during execution, but I think I've never actually needed to do that.

提交回复
热议问题