1

在我的 Window Service 应用程序中,计时器函数永远不会被调用。我在我的机器上部署了该服务,然后将该服务附加到 Visual Studio,并在不同功能上设置断点。在OnStart()没有调用我的任何函数之后。

这是我的OnStart()功能

protected override void OnStart(string[] args)
{
    this.timer = new System.Timers.Timer(50000);
    this.timer.AutoReset = true;
    this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
    this.timer.Start();
}

2017 年 9 月 12 日更新:在 try and catch 中添加了事件日志, 然后调用此函数timer1_tick()

 private void timer1_Tick(object sender, EventArgs e)
 {
     try
     {
         EventLog.WriteEntry("Running.."+ e.ToString());
     }
     catch (Exception ex)
     {
         EventLog.WriteEntry("Caught Exception "+ex.ToString(), EventLogEntryType.Error);
     }
 }

timer1_tick永远不会被调用。有什么建议么?

2017 年 12 月 9 日更新:我检查了事件日志。在 Windows 日志 > 应用程序下,我可以看到消息,服务已成功启动。但是,不会显示在 try-catch 块中添加的事件日志。不确定我是否遗漏了什么。

我将该服务附加到 Visual Studio 以进行调试。在下图中,OnStart()调用了该方法。我刚刚添加了,Thread.Sleep(30000)以便我有一些缓冲时间将进程附加到调试器以避免跳过该OnStart()函数

在此处输入图像描述

定时器启动后,我在 TimerTick() 函数上有一个断点,希望它被击中,但它从来没有

在此处输入图像描述

4

1 回答 1

2

timer1_Tick很可能被称为你的一切OnStart似乎都合适。也许您没有收到电子邮件的原因是因为_SendEmail抛出了异常。

写信EventLog可能会提供更多信息?

private void timer1_Tick(object sender, EventArgs e)
{
    try
    {
        SendMail._SendMail("Processing A started at" + DateTime.Now.ToString());
        Logging.log.LogInput("start refund process");
    }
    catch (Exception ex)
    {
        EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
    }
}

作为最佳实践,我也会写信到EventLoginOnStartOnStop.

protected override void OnStart(string[] args)
{
    // Log a service start message to the Application log.
    EventLog.WriteEntry("My Service in OnStart.");

    timer = new System.Timers.Timer(50000);
    timer.AutoReset = true;
    timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
    timer.Start();
}

protected override void OnStop()
{
    // Log a service stop message to the Application log.
    EventLog.WriteEntry("My Service in OnStop.");
}
于 2017-09-11T17:21:46.687 回答