How to have a loop in a Windows service without using the Timer

前端 未结 5 897
清歌不尽
清歌不尽 2020-11-29 01:29

I want to call a Business layer method from a Windows service (done using C# and .NET) after every 10 seconds. However, i dont want to use the Timer_Elapsed event since it s

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 02:26

        Thread thread;
        private void DoWork(object arg)
        {
            while (true)
            {
                // Run this code once every 20 seconds or stop if the service is stopped
                try
                {
                    Thread.Sleep(20000);
                    //Do work....
                }
                catch(ThreadInterruptedException)
                {
                    return;
                }
    
            }
        }
    
        protected override void OnStart(string[] args)
        {
            // Start the thread
            thread = new Thread(DoWork);
            mWorker.Start();
        }
    
        protected override void OnStop()
        {
            // interrupt thread and wait until it does
            thread.Interrupt();
            thread.Join();
        }
    

提交回复
热议问题