C # object garbage collection declared in constructor

In the following code, I create a DispatcherTimer in the class constructor. No one refers to it.

In my understanding, the timer should be returned by the garbage collector some time after leaving the constructor area. But this does not happen! Even after forced garbage collection withGC.Collect()

What happens 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();
        };
    }
}
+5
source share
3 answers

When you simply create a DispatcherTimer, nothing prevents it from being GCed. However, you set IsEnabled = truewhich will call Start()on the timer. When this happens, this line of code will be executed:

this._dispatcher.AddTimer(this);

Dispatcher , GCed.

+3

, ,

this.timerRoot = GCHandle.Alloc(this);


EDIT:

, DispatcherTimer - , ( Dispatcher), ...

+4

It will be added to the queue Dispatcherto be deployed.

+1
source

All Articles