Reputation: 26919
I have an assembly that have drag dropped a COM Interop VB 6.0 text editor in it and been using it as a .NET wrapped control... Then in a new assembly that is a windows form I drag drop the assembly above and start using it, declare a variable of it and assign event handlers to it so for example if Assmbley abvoe is namved MyTextControl then in this windows form I have a variable of mytxtcntrl and some event handlers for it like
mytxtcntrl.TextEditor.ObjectDblClicked += new AxTextEditorLib._DTextEditorEvents_ObjectDblClickedEventHandler(ctlTEEditor_ObjectDblClicked);
So now Sholud I even worry about removing these event handlers with "-=" ? or GC will take care of it? If I should do it manually then what is the correct place to do it? I put them in Form_Closed section and ran a memory profiler, it didn't have any effect.
Upvotes: 1
Views: 303
Reputation: 941218
Unsubscribing events explicitly is only required when the event source object outlives the event subscriber. Not doing so will keep a reference to the objects that subscribe, preventing them from being garbage collected.
Winforms was pretty carefully designed to avoid that kind of mishap. You'd normally write an event handler in a form or user control to listen to events fired by the child controls. The lifetime of those child controls is closely associated with the lifetime of the form, they all get disposed at the same time when the user closes the form. The garbage collector will not be stumped by this and collects them all at the same time.
Your ActiveX control fits this pattern, it will be a child control of your form so dies at the exact same time the form dies. No need for explicit cleanup at all.
There are a few corner cases where this will not work as described. A classic one is where you remove a control yourself in your own code but keep the form alive. Now you should unsubscribe any events to allow that control to be garbage collected. And most importantly, you have to explicitly call Dispose() on the control as well to ensure the native window for it is destroyed. Not doing so produces a permanent leak that not even the garbage collector can solve, a control is kept alive by its window handle.
The second case is the SystemEvents class. Its events are static, the class object lives until your program terminates. You always have to explicitly unsubscribe its events if you use them in a form that may be closed without otherwise terminating the app.
Upvotes: 3
Reputation: 5760
No, you shouldn't. The GC will take care of it. The only place where you need to worry about "trowing away" objects, is when you are using a class which implements IDisposable
or when you're doing stuff with System.Runtime.InteropServices
.
Upvotes: 2