C # Windows Service to perform infinite loop

When written with C # Windows Service, polling there are two ways, one is to use Timer, System.Timers or System.Thread in this cycle execution time is execution, the disadvantage is perhaps not the last execution complete, it began to implement the new.

Another way is to use threads in OnStart in a single open thread to run a function containing an infinite loop structure, the disadvantage of this approach is difficult to control thread, stop the service, there may be a thread in execution, resulting in service can not be stopped and restarted.

But .Net 4.0+ provides us CancellationTokenSource, to cancel the thread (Task) is running, the code:

CancellationTokenSource cancelTokenSource = new CancellationTokenSource();

        protected override void OnStart(string[] args)
        {
            Logger.Instance.WriteLine("{0} is start.", base.ServiceName);
            Task.Factory.StartNew(DoWork, cancelTokenSource.Token);
        }

        protected override void OnStop()
        {
            cancelTokenSource.Cancel();
            cancelTokenSource.Dispose();
            Logger.Instance.WriteLine("{0} is stop.", base.ServiceName);
        }

        private void DoWork(object arg)
        {
            while (!cancelTokenSource.IsCancellationRequested)  // Worker thread loop
            {
                Logger.Instance.WriteLine("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
                System.Threading.Thread.Sleep(2000);
            }
        }

 

Guess you like

Origin www.cnblogs.com/HansZimmer/p/11262079.html