简体   繁体   中英

System.timer doesnt throw events and console terminates immediatly

I need a timer that executes every minute but i have trouble getting the timer to run at all with code that i used before. so i guess i am doing sth fundamentally wrong that is not code related but even in a just newly created Console project in visual studio community 2017 it doesn't execute the _timer_elapsed method. the console terminates immediately without errors as if it has executed every code

using System;
using System.Timers;

namespace Test
{
    class Program
    {

        static Timer _timer;

        public static void Main(string[] args)
        {
            var timer = new Timer(60000);
            timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            timer.Enabled = true;
            _timer = timer;
        }
        static void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("test");
        }
    }
}

what am I missing here?

You need your program to stay alive, rather than return from Main . An quick and easy way to do this is to wait for some input at the end:

public static void Main(string[] args)
{
    var timer = new Timer(60000);
    timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
    timer.Enabled = true;
    _timer = timer;

    Console.ReadLine();
}

There is no such thing as a bad question. (Though some questions show more affinity with programming, and some show less.)

If you look at your code, your main sets up a timer and then proceeds to terminate. So, of course your program exits immediately and the timer is never fired.

In order to see your timer firing, your program will need to keep running for at least as long as one period of your timer.

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