2017-08-16 101 views
0

我创建了.net Windows服务,并计划每5分钟运行一次。 此Windows服务包含发送电子邮件并在发送电子邮件后更新表的代码。计时器如何在.net Windows服务中工作?

首先我发送所有的电子邮件,然后更新数据库中的所有记录bulk.So我的问题是我设置的间隔为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 
+0

_Which_'Timer' class? .NET定义了4种不同的方法,并且可能使用不正确的方法 – MickyD

+2

[了解C#中Timer控件的工作方式]的可能副本(https://stackoverflow.com/questions/8997838/understanding-working-of-timer-control- in-c-sharp) –

+0

这不是一个控件。 AutoReset = true是相当危险的,并且*即使在前一个滴答未完成时也会导致Elapsed事件处理程序运行。这很少会达到一个好结局。很容易修复,使用false并在事件处理程序结束时设置Enabled = true。在事件处理程序中始终使用try/catch来确保不会吞下异常。 –

回答

-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(); 
+0

所有可能导致的结果都是不受欢迎的_re-entrancy_ – MickyD

+0

我会尝试下面的代码并查看_timer.Stop(); {//每次发送一封电子邮件..这是循环 Library.SendEmail(edtls); ds.Tables [“EDts”]。Rows [i] [“Sent”] = 1; ds.Tables [“EDts”]。行[i] [“状态”] =“发送”;ds.Tables [“EDts”] .Rows [i] .EndEdit(); } ..定时器在这里停止执行(它发送的电子邮件,但不更新表)012sds.Update(EDts,“EmailDts”);//在这里更新表 _timer.Start(); – user8383606

+0

是否可以在发送每封电子邮件时调用数据库更新,因为如果我发送了100封电子邮件,并且发送了90封电子邮件并且剩余的问题出现了,它也不会更新90封电子邮件。 – user8383606