In the following code, I create a DispatcherTimer in the class’s constructor. No one keeps reference on it.
In my understanding, the timer should be reclaimed by the garbage collector some time after leaving the constructor’s scope.
But that doesn’t happen! Even after forcing a garbage collection with GC.Collect()
What is going on under the hood?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(100),
IsEnabled = true
}
.Tick += (s, e) =>
{
textBlock1.Text = DateTime.Now.ToString();
};
}
}
When you just construct the a
DispatcherTimer, nothing prevents it from be GCed. However, you setIsEnabled = true, which will callStart()on the timer. When that, happens, this line of code will be executed:And now the
Dispatcheritself is rooting the timer, meaning it can’t be GCed.