简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM