定时器代码没错误但不运行

ccbbcc 2024-10-22 13:58:38

代码:

using System;
using System.Timers;

class Program
{
    private static Timer aTimer;
    private static int counter = 0;

    static void Main(string[] args)
    {
        // 创建一个定时器,设置时间间隔为1000毫秒(1秒)  
        aTimer = new Timer(1000);

        // 绑定事件处理方法  
        aTimer.Elapsed += OnTimedEvent;

        // 设置是否重复触发  
        aTimer.AutoReset = true;

        // 启动定时器  
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        // 在这里编写定时执行的代码  
        counter++;
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
        Console.WriteLine("Counter: " + counter);
    }
}

 请问专家,为什么没有输出?谢谢

 

...全文
91 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
特别 02-19
  • 打赏
  • 举报
回复

这段代码没问题啊,你这个运行的结果正常啊。
调试的时候,他会弹出一个控制台的新窗口,内容显示在控制台中。

我怀疑你建立的项目不对,你可能建立的是windows Form项目,但实际要建一个控制台项目。
如果你头铁的话,可以改成这样:
主要是最后加一行:Application.Run();

using System;
using System.Timers;
using System.Windows.Forms;

    static class Program
    {

        private static System.Timers.Timer aTimer;
        private static int counter = 0;

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            // 创建一个定时器,设置时间间隔为1000毫秒(1秒)  
            aTimer = new System.Timers.Timer(1000);

            // 绑定事件处理方法  
            aTimer.Elapsed += OnTimedEvent;

            // 设置是否重复触发  
            aTimer.AutoReset = true;

            // 启动定时器  
            aTimer.Enabled = true;

            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();
            Application.Run();  
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            // 在这里编写定时执行的代码  
            counter++;
            Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", e.SignalTime);
            Console.WriteLine("Counter: " + counter);
        }
}


111,077

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧