iuristona
iuristona

Reputation: 927

Timer executes just a few times

I am trying to run a timer every hour.

This code runs normally, but only a few times, then it stops. I can't figure out why.

using System.Threading.Tasks;

class Program
{    
    static void Main(string[] args)
    {    
        var timer = new Timer(Execute,
            null,
            TimeSpan.Zero,
            //TimeSpan.FromSeconds(10)
            TimeSpan.FromHours(1)
        );

        // Wait press <Enter> to execute or <Esc> to exit
        while (true) {
            var key = Console.ReadKey().Key;
            if (key == ConsoleKey.Enter)
                Execute(null);
            else if (key == ConsoleKey.Escape)
                break;
        }
    }

    private static async void Execute(object e)
    {
        ...
        await Proc(e);
    }
}

Upvotes: 0

Views: 74

Answers (1)

JeffRSon
JeffRSon

Reputation: 11186

There is a chance, that timer is garbage collected.

Define it outside of Main() to keep a reference during the whole life time of the process.

You might use GC.KeepAlive(timer) at the end of Main() as well.

Upvotes: 2

Related Questions