Q:

C# Timer stopping

For a test I set up a class that simply counts up an int every second:
class TestComp1
{
    public TestComp1()
    {
        var timer = new Timer(o => TestInt++,null,0,1000);
    }

    [ViewableProperty]
    public int TestInt { get; set; } = 0;
}

The problem is that this Timer seems to stop working after roughly one minute.
If I rewrite it to use a Thread instead it keeps working. So it really seems to be the timer that stops.
Does anyone have an idea as to why this happens?

A:

You have no reference to the timer outside of the scope of the constructor. The moment the constructor is finished the timer is no longer referenced and will be collected by the garbage collector.
You can fix it by using a field for the timer (or anything else that prevents not having a reference where you need the timer.)
class TestComp1
{
    private Timer _timer;

    public TestComp1()
    {
        _timer = new Timer(o => TestInt++,null,0,1000);
    }

    [ViewableProperty]
    public int TestInt { get; set; } = 0;
}

