【问题标题】:How timer works in .net windows service?计时器如何在.net windows 服务中工作?
【发布时间】:2017-08-18 01:42:39
【问题描述】:

我创建了 .net Windows 服务,并安排它每 5 分钟运行一次。 此 Windows 服务包含发送电子邮件并在发送电子邮件后更新表格的代码。

首先我发送所有电子邮件,然后批量更新数据库中的所有记录。所以我的问题是我将间隔设置为 5 分钟,它是否会破坏我的场景,例如发送电子邮件需要 5 分钟,然后是计时器在不更新数据库的情况下停止,或者继续执行直到完全执行任务。

_timer = new Timer(5* 60 * 1000);   
 _timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
_timer.AutoReset = true;
 _timer.Start();

.......................

{//send one email at a time ..this is in loop
Library.SendEmail(edtls);   

ds.Tables["EDts"].Rows[i]["Sent"] = 1;
ds.Tables["EDts"].Rows[i]["Status"] = "Sent";   
ds.Tables["EDts"].Rows[i].EndEdit();
}..how about timer stop execution here(it sends the emails but doesn't update the table)
ds.Update(EDts, "EmailDts");//updating table here

【问题讨论】:

  • 哪个 Timer 类? .NET 定义了 4 种不同的,有可能使用不正确的
  • 它不是控件。 AutoReset = true 非常危险,并且 导致 Elapsed 事件处理程序运行,即使前一个滴答尚未完成。这很少有好的结局。修复简单,使用 false 并在事件处理程序末尾设置 Enabled = true。始终在事件处理程序中使用 try/catch 以确保不吞噬异常。

标签: c#


【解决方案1】:

是的,所以如果发送电子邮件或数据库更新所花费的时间比定时器事件触发的时间长,这可能会很棘手。您可以在两者之间停止计时器并在之后继续。

_timer.Stop();
{//send one email at a time ..this is in loop
Library.SendEmail(edtls);   

ds.Tables["EDts"].Rows[i]["Sent"] = 1;
ds.Tables["EDts"].Rows[i]["Status"] = "Sent";   
ds.Tables["EDts"].Rows[i].EndEdit();
}..how about timer stop execution here(it sends the emails but doesn't update the table)
ds.Update(EDts, "EmailDts");//updating table here
_timer.Start();

【讨论】:

  • 所有可能导致的结果都是不可取的重新进入
  • 我将尝试下面的代码并查看 _timer.Stop(); {//一次发送一封电子邮件..这是在循环 Library.SendEmail(edtls); ds.Tables["EDts"].Rows[i]["Sent"] = 1; ds.Tables["EDts"].Rows[i]["Status"] = "Sent"; ds.Tables["EDts"].Rows[i].EndEdit(); }..这里计时器停止执行怎么样(它发送电子邮件但不更新表) ds.Update(EDts, "EmailDts");//在这里更新表_timer.Start();
  • 是否可以在发送的每封电子邮件上调用 db update,因为如果我发送了 100 封电子邮件并且发送了 90 封电子邮件并且剩下的有问题,它也不会更新 90 封电子邮件。请建议。
猜你喜欢
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多