Quote from C# language specification 3.9:
‘2. If the object, or any part of it, cannot be accessed by any possible
continuation of execution, other than
the running of destructors, the object
is considered no longer in use, and it
becomes eligible for destruction…
For instance would the DispatcherTimer be eligible for garbage collection before the Tick event fires?
public void DispatchCallbackAfter(Action callback, TimeSpan period)
{
DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Normal, AppSettings.MainWindow.Dispatcher);
timer.Tick += new EventHandler(DispatchCallback);
timer.Interval = period;
timer.Tag = new object[] {timer, callback};
timer.Start();
}
private void DispatchCallback(object sender, EventArgs args)
{
DispatcherTimer t = (DispatcherTimer)sender;
t.Stop();
((Action)((object[])t.Tag)[1])();
}
NOTE: There is self reference to the timer in timer.Tag but I imagine that would not make any difference?
While the
DispatcherTimeris running, theDispatcherhas a reference to it, and it will not get GCed. Once the timer stops and there is no external reference to it, it can be collected. That is, if your only references to the timer and the callback are within the timer and the callback, and the timer is stopped, the timer can be collected.You can tell that the dispatcher takes a reference to a running timer by looking in Reflector (or your favorite decompiler) and seeing that the timer calls
_dispatcher.AddTimer(this);in its start function and_dispatcher.RemoveTimer(this);in its stop function.