events & destructor

  • Thread starter Thread starter lukasz
  • Start date Start date
L

lukasz

When I attach an event handler (e.g. button.Click += new
EventHandler(Button_Clicked)) it's not necessary to remove the handler when
my class (or form) gets disposed or destroyed, is it? When my class gets out
of its scope and its time for GC-ing comes, it will be able to be destroyed
despite the "active" event handler?
 
As soon as the Form becomes unreachable, that is, you have no
references to the Form object left, then the GC can clean up both the
form and the event handler (delegate) the Form references (assuming
the delegate in also unreachable). So no, you should not need to
remove the event handler.

HTH,
 
How about the situation with two objects, ObjUser and ObjService, ObjService
valid throughout the life span of the application and ObjUser being created
for a short time at certain moments. Now when I write in ObjUser's creator:

ObjService.OnChanged += new EventHandler(this.xxxx)

do I need to explicitly remove this handler? ObjService will still be in use
when ObjUser gets out of its scope.
 
Hi lukasz:

In this case you might want to explicitly remove those handlers. If I
understand what you are saying - the Service will keep a reference to
the delegate and prevent it from being collected, and the delegate
holds a reference to to objUser which keeps objUser around.
This is an unfortunate scenario, you might want to google for "weak
reference delegate" as I believe some people have written code to
address the issue.
 
Back
Top