Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

c# - Do Timer object get GC-ed when no other object references them?

Can an object containing an active Timer (System.Timers.Timer) be garbage collected, if no other object is referencing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two basic ways that a Timer stays referenced even if you don't store a reference somewhere:

  • As long as the timer is enabled. There's an underlying System.Threading.Timer that actually generates the event. The CLR keeps a list of active timers, the callback delegate object of them keeps the Timer referenced.

  • By the Elapsed event handler if it is not static. That extends the lifetime of the Timer instance to at least the lifetime of the class object that contains the Elapsed event handler.

There is no failure mode here. The only possible way to get a reference back to the timer is through the Elapsed event handler's sender argument. If you disable the timer then there is no longer a way to get a reference so it is appropriate for the object to be collected.

A fairly classic way to get in trouble with this Timer and lose Elapsed events is when you have the AutoReset property set to false. A very nasty issue is that any exceptions raised in the Elapsed event handler are swallowed without any diagnostic. Which will bypass the call you'd have to restart the timer at the end. Do favor System.Threading.Timer, it doesn't have this problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...