Polling Service - C#

前端 未结 2 736
無奈伤痛
無奈伤痛 2020-12-17 06:15

Will anobody be able to help me?

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 up

相关标签:
2条回答
  • 2020-12-17 07:08

    Set Timer.AutoReset = true. otherwise it will do its work only one time. but it's better to work with threading in windows services.

    [edit] ah, yes. autoreset is true in default. I put this too in my code: GC.KeepAlive( myTimer ); so the gc won't remove it if it is inactive.

    0 讨论(0)
  • 2020-12-17 07:10

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

    i.e.

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

    In your Service

        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();
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题