Alternatives to Thread.Sleep()

后端 未结 11 1280
清歌不尽
清歌不尽 2020-11-27 03:48

Every N minutes we want to run through a list of tasks. So we\'ve created a task executor with a

do { DoWork(); }while(!stopRequested)

No

11条回答
  •  天涯浪人
    2020-11-27 04:27

    As other answerers have said, Timers may work well for you.

    If you do want your own thread, I wouldn't use Thread.Sleep here, if only because if you need to shut down the application, there's no good way to tell it to exit the sleep. I've used something like this before.

    class IntervalWorker
    {
        Thread workerThread;
        ManualResetEventSlim exitHandle = new ManualResetEventSlim();
    
        public IntervalWorker()
        {
            this.workerThread = new Thread(this.WorkerThread);
            this.workerThread.Priority = ThreadPriority.Lowest;
            this.workerThread.IsBackground = true;
        }
    
        public void Start()
        {
            this.workerThread.Start();
        }
    
        public void Stop()
        {
            this.exitHandle.Set();
            this.workerThread.Join();
        }
    
        private void WorkerThread()
        {
            int waitTimeMillis = 10000; // first work 10 seconds after startup.
    
            while (!exitHandle.Wait(waitTimeMillis))
            {
                DoWork();
    
                waitTimeMillis = 300000; // subsequent work at five minute intervals.
            }
        }
    }
    

提交回复
热议问题