C#窗口服务未调用计时器功能
在我的窗口服务应用程序中,从未调用计时器函数。我在我的机器上部署了该服务,然后将该服务附加到VisualStudio,并在不同的函数上设置断点。在C#窗口服务未调用计时器功能,c#,windows-services,system.timers.timer,C#,Windows Services,System.timers.timer,在我的窗口服务应用程序中,从未调用计时器函数。我在我的机器上部署了该服务,然后将该服务附加到VisualStudio,并在不同的函数上设置断点。在OnStart()之后,不会调用我的任何函数 这是我的OnStart()函数 protected override void OnStart(string[] args) { this.timer = new System.Timers.Timer(50000); this.timer.AutoReset = true; thi
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年12月9日更新:在try and catch中添加了事件日志
然后,此函数调用timer1\u tick()
:
永远不会调用计时器1\u勾选
。有什么建议吗
更新2017年9月12日:我查看了事件日志。在Windows日志>应用程序下,我可以看到消息“服务已成功启动”。但是,不会显示在try-catch块中添加的事件日志。不确定我是否遗漏了什么
我将该服务附加到VisualStudio进行调试。在下图中,调用了OnStart()
方法。我刚刚添加了Thread.Sleep(30000)
,以便获得一些缓冲时间将进程附加到调试器,以避免跳过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();
}
计时器启动后,我在TimerTick()函数上有一个断点,希望它被命中,但它从未被命中
timer1\u Tick
可能会被调用,因为启动时的中的所有内容似乎都是合适的。您没有收到电子邮件的原因可能是\u sendmail
引发了异常
写入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);
}
}
作为最佳实践,我还将在OnStart
和OnStop
中写入EventLog
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.");
}
你等得够久了吗?可能是个愚蠢的问题,但你永远不会知道:)尝试以较低的间隔初始化,并在计时器1_刻度内放置一个Try\catch,如果发生异常,则记录异常。@MartinoBordin I将间隔缩短为5秒,并添加了一个Try-catch块,但是我没有收到电子邮件。没有收到电子邮件并不意味着没有调用timer1\u Tick方法。可能会将timer1\u Tick函数更改为private void timer1\u Tick(对象发送方,ElapsedEventArgs e)。尽管这不太可能是原因,但请尝试一下?我按照您的建议添加了事件日志。我甚至在try块中添加了它们,但事件查看器不显示任何消息。它表明服务已成功启动,但之后什么也没有。@AnanthKumble您的问题不在您提供的代码中。我创建了一个简单的服务,里面除了计时器什么都没有,它按预期工作。您的服务是否仍在运行,可能正在崩溃?该服务将继续运行。甚至我也创建了一个不同的窗口服务项目,并按预期调用了计时器函数。我正在尝试修复现有窗口服务项目中的问题