C#窗口服务不调用定时器功能
在我的Window服务应用程序中,定时器功能从不被调用。我将服务部署在我的机器上,然后将服务连接到Visual Studio,并使用不同功能的断点。在OnStart()
之后,我的功能都没有被调用。C#窗口服务不调用定时器功能
这是我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日:添加的事件登录尝试,赶上 然后,这个函数调用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
很可能被称为一切都在你的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);
}
}
正如我还要写EventLog
在OnStart
和OnStop
的最佳实践。
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.");
}
我按照你的建议添加了事件日志。我甚至将它们添加到try块中,但事件查看器不显示任何消息。它显示服务已成功启动,但没有任何提供。 –
@AnanthKumble您的问题不在您提供的代码中。我创建了一个没有任何内容的简单服务,但计时器和预期的工作。你的服务是否继续运行,也许它正在崩溃? –
服务继续保持运行。即使我创建了一个不同的Window Service项目,并按预期调用了定时器函数。我正在尝试解决现有窗口服务项目中的问题 –
你确实等了很久?愚蠢的问题,但你永远不会知道:) –
尝试用较低的时间间隔进行初始化,并将try \ catch放入timer1_Tick中,如果发生异常,则记录该异常。 –
@MartinoBordin我把间隔减少到5秒,并添加了一个try-catch块,但我没有收到电子邮件。 –