Csharp/C#教程:投票服务 – C#分享


投票服务 – C#

有人能帮助我吗?

我正在创建一个连接到SQL数据库的Windows服务,并检查表中的日期并将其与今天的日期进行比较,并更新该数据库中的字段,例如,如果日期等于今天的日期,则该字段将设置为true 。

我遇到的问题是,当我启动服务时,它不会这样做但是当我以正常forms执行它时它完美地工作。

我的代码如下:

//System.Timers Timer timer = new Timer(); protected override void OnStart(string[] args) { timer.Elapsed += new ElapsedEventHandler(OnElapsedTime); timer.Interval = 60000; timer.Enabled = true; } private void OnElapsedTime(object source, ElapsedEventArgs e) { int campid = 0; var campRes = new ROS.Process.CampaignServiceController().GetCampainInfo(); foreach (var s in campRes) { campid = s.CampaignId; if (s.CampEndDate.Date < DateTime.Today.Date) { //WriteDataToFile("Not Active : " + campid.ToString()); new ROS.Process.CampaignServiceController().SetCampainStatusFalse(campid); } else { //WriteDataToFile("Active : " + campid.ToString()); new ROS.Process.CampaignServiceController().SetCampainStatusTrue(campid); } } } 

另一种方法是等待事件而不是使用计时器。

  public class PollingService { private Thread _workerThread; private AutoResetEvent _finished; private const int _timeout = 60*1000; public void StartPolling() { _workerThread = new Thread(Poll); _finished = new AutoResetEvent(false); _workerThread.Start(); } private void Poll() { while (!_finished.WaitOne(_timeout)) { //do the task } } public void StopPolling() { _finished.Set(); _workerThread.Join(); } } 

在您的服务中

  public partial class Service1 : ServiceBase { private readonly PollingService _pollingService = new PollingService(); public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { _pollingService.StartPolling(); } protected override void OnStop() { _pollingService.StopPolling(); } } 

设置Timer.AutoReset = true。 否则它只能完成一次工作。 但最好在Windows服务中使用线程。

[编辑]啊,是的。 autoreset默认为true。 我把它放在我的代码中:GC.KeepAlive(myTimer); 所以如果它不活动,gc将不会删除它。

上述就是C#学习教程:投票服务 – C#分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1045310.html

(0)
上一篇 2022年2月5日
下一篇 2022年2月5日

精彩推荐