简体   繁体   English

System.timer 不会抛出事件并且控制台会立即终止

[英]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.所以我想我从根本上做错了,这与代码无关,但即使在 2017 年 Visual Studio 社区中刚刚创建的控制台项目中,它也不会执行_timer_elapsed方法。 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 .你需要你的程序保持活力,而不是从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.为了看到您的计时器触发,您的程序需要至少持续运行一个计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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