111,077
社区成员




代码:
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);
}
}
请问专家,为什么没有输出?谢谢
这段代码没问题啊,你这个运行的结果正常啊。
调试的时候,他会弹出一个控制台的新窗口,内容显示在控制台中。
我怀疑你建立的项目不对,你可能建立的是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);
}
}