轮询服务 - C# [英] Polling Service - C#

查看:23
本文介绍了轮询服务 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能帮我吗?

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

I am creating a windows service that connects to a sql database and checks a date in the table and compares it to todays date and updates a field in that database for eg if the date is equal to todays date then the field will be set to true.

我遇到的问题是,当我启动服务时,它不会这样做,但是当我以正常形式运行时,它可以完美运行.

The problem I am having is that when i start the service it does not do that but when i do it in a normal form it works perfectly.

我的代码如下:

//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);
        }
    }
}

推荐答案

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

Another way of doing this would be to wait on an event rather then using a timer.

    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();
        }

    }

这篇关于轮询服务 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆