【发布时间】:2018-02-19 23:21:29
【问题描述】:
在我的 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 永远不会被调用。有什么建议吗?
12/09/2017 更新:我检查了事件日志。在 Windows 日志 > 应用程序下,我可以看到消息,服务已成功启动。但是,不会显示在 try-catch 块中添加的事件日志。不确定我是否遗漏了什么。
我将该服务附加到 Visual Studio 以进行调试。在下图中,调用了OnStart() 方法。我刚刚添加了Thread.Sleep(30000),以便获得一些缓冲时间来将进程附加到调试器以避免跳过OnStart() 函数
定时器启动后,我在 TimerTick() 函数上有一个断点,希望它被命中,但它永远不会被命中
【问题讨论】:
-
你等得够久了吗?可能是愚蠢的问题,但你永远不会知道:)
-
尝试以较低的时间间隔进行初始化,并在 timer1_Tick 中放置一个 try\catch,如果发生则记录异常。
-
@MartinoBordin 我将间隔减少到 5 秒并添加了一个 try-catch 块,但我没有收到电子邮件。
-
收不到邮件并不意味着没有调用 timer1_Tick 方法。
-
也许将 timer1_Tick 函数更改为私有 void timer1_Tick(object sender, ElapsedEventArgs e)。尽管这不太可能是原因,但请尝试一下?
标签: c# windows-services system.timers.timer