-
November 30th, 2009, 06:56 AM
#1
Disposal of event handlers
When I use the designer to generate Event Handlers for my Click events it adds a line of code which adds a delegate instance to the event eg
this.button1 = new System.Windows.Forms.Button();
this.button1.Click += System.EventHandler (this.button1_Click);
However, the designer does not provide the code which removes the event handler from the Click event.
Does this mean that when I add my own event handlers, using the += syntax, I also do not have to remove them using the -= syntax? Or will this cause memory leaks?
Thanks in advance
-
November 30th, 2009, 09:05 AM
#2
Re: Disposal of event handlers
Simply: it depends. Event handlers generated by the designer is local to the form, so if the instance of the is GC'ed out, they cannot be more executed. Also, it is supposed that no more events can occure on closed form, because form's events are related to GUI. If you attach your own handler, especially on you own event, it is upon you to ensure that is (not) called properly. If the target method of the event handler (keep in mind it is a delegate) belongs to other instance, it can cause memory leaks if it is not properly detached.
- Make it run.
- Make it right.
- Make it fast.
Don't hesitate to rate my post.
-
December 1st, 2009, 06:59 AM
#3
Re: Disposal of event handlers
Originally Posted by Rachel888s
However, the designer does not provide the code which removes the event handler from the Click event.
Indeed, it is a reasonable expectation that you wouldnt want to unlink an event handler you have linked at design time
Does this mean that when I add my own event handlers, using the += syntax, I also do not have to remove them using the -= syntax? Or will this cause memory leaks?
As Bou says, it depends on how long you expect your object raising the event, to last. It is reasonable to expect that the form will last the life of the app and so its event handler will be linked all that time.. If you tell us more about the life of the object that raises events and why sometimes you might not want to listen to them, we can tell you if you need to remove the handlers or not
-
December 1st, 2009, 07:38 AM
#4
Re: Disposal of event handlers
The object will be raising the event for the lifetime of my Tab Control which is displayed on a Tab Page. I have now implemented a method which is called on closing the property page that unregisters the event handler.
Thanks for your help.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|