I
I
isxaker2014-03-05 10:41:10
.NET
isxaker, 2014-03-05 10:41:10

Do I need to unsubscribe from events in .net winforms app?

I am currently writing a winforms app. For example, if I subscribed to an event in the form constructor, do I need to unsubscribe from it and when? If not, why not?

public partial class Main: Form {
        public Main() {
        	InitializeComponent();
    this.tree.FilterNode += OnFilterNode;
        }
}

It is clear that if I design my own classes (notifier and subscriber), I will have to unsubscribe from events manually, for example, in the Dispose () method. Here is the question about winforms.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aush, 2014-03-05
@isxaker

It is impossible to give a general answer to this question.
Usually , when you subscribe to child control events in the constructor (or on Load) of a form, there is no need to unsubscribe from them.
But, if the event handler contains a reference to an object whose lifetime is less than the lifetime of the form, then it will not be collected by the garbage collector before the event is unsubscribed. In this case, you should have some kind of event that tells you that the object is no longer in use and clears your subscriptions in response to that event.
Simply put, a third party will initiate the cleanup of the subscription. Your form's designer.cs already has a Dispose() which is usually called by the "third party" (WinForms framework), so you don't need to think about it in most cases.
Most likely, if you now have such a question, then you really should not think about unsubscribing from such events, and when you have a task of the appropriate level, you yourself will be able to figure out when to unsubscribe.

L
Lindvorn, 2014-03-05
@Lindvorn

Events are essentially wrappers for delegates. Delegates have an internal list that can be obtained by calling the Delegate.GetInvocationList() method. Recommendations for unsubscribing from events are justified by the fact that memory leaks do not occur in the case when the object is no longer used, but somewhere in the Invokation list a reference to the object is still stored (something like that).
In general, in your case there is no need to unsubscribe. (Of course, I can be wrong about this and it's better to check it with a small experiment)
Richter has this very well described in any of his books "CLR via C#".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question