Timer Elapsed 事件未命中目标方法

Timer Elapsed Event not hitting targeted method

我正在开发 Windows 服务,在 OnStart() 方法中我使用 Timer 在一定时间间隔后点击 timer1_Tick,但 timer1_Tick 没有调用哪怕只有一次。

这是我的代码

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    var timer1 = new System.Timers.Timer();
    timer1.Interval = 30000; //every 30 secs
    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
    timer1.Enabled = true;
    WriteToFile("Service has started..");
}

private void timer1_Tick(object sender, ElapsedEventArgs e)
{
    WriteToFile("Entered in GetFailedProductDetails...");
    //code  
}

widows 服务的起始代码Program.cs 文件

static class Program
{
    static void Main()
    {
        Service1 myService = new Service1();
        //myService.OnDebug();           
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        };
        ServiceBase.Run(ServicesToRun);
    }      
}   

您的计时器可能会被垃圾回收系统回收,因为您没有保留对它的引用。

你应该把它存储在一个字段中:

private System.Timers.Timer timer1;

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    timer1 = new System.Timers.Timer();
    timer1.Interval = 30000; //every 30 secs
    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
    timer1.Enabled = true;
    WriteToFile("Service has started..");
}