Events and Dispose

M

mick

Anyone put this straight in my head...

If you dispose an object that without explicitly removing the event
subscription
what happens? Does the event still hang there? Does it prevent the
Dispose()?
If so, what is the point of subbing to an event using an anon. method?

Timer timer = new Timer();
timer.Interval = 2000;
timer.Tick += (s,e) => {
// DO Stuff
timer.Dispose();
};
timer.Start();



mick
 
A

Adam Clauss

If you dispose an object that without explicitly removing the event
subscription
what happens? Does the event still hang there? Does it prevent the
Dispose()?
If so, what is the point of subbing to an event using an anon. method?

Timer timer = new Timer();
timer.Interval = 2000;
timer.Tick += (s,e) => {
// DO Stuff
timer.Dispose();
};
timer.Start();
Two items of interest here:
1) The instance of the timer
2) The instance of your anonymous method

The dispose call is somewhat irrelevant actually. Dispose does not get
rid of the Timer instance, it simply tells the timer to clean up it's
internal resources. That is completely indepenent of the timer / event
/ anonymous method hanging around. The timer instance itself will still
exist and needs to be garbage collected at some point.

More important is when do YOU get rid of any references to "timer" (aka
set to null)?

The timer holds a reference to the anonymous method (via the Timer's
Tick event), so until the timer goes away, the anonymous method cannot
go away. Once all your references to the timer are gone, the timer is
eligible for garbage collection. Once the timer gets garbage
collected*, there will be no more references to the anonymous method and
the anonymous method will then become eligible for garbage collection.

* Qualifying this statement slightly: The GC may "optimize" the process
by recognizing (in the same GC pass) that the "chain" of objects from
Timer -> Tick Event -> anonymous method have no more references and can
be garbage collected all at once (rather than making the Timer go in a
initial pass, and the anonymous method in a later pass). I don't know,
but in either case, it is a tangent and not particularly important to
your question.

-Adam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top