Alternatives to Thread.Sleep()

后端 未结 11 1285
清歌不尽
清歌不尽 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条回答
  •  旧时难觅i
    2020-11-27 04:30

    I would use a waiting timer which signals an AutoResetEvent. Your thread should wait for this WaitHandle object. Here is a small console app showing this approach:

    class Program {
        const int TimerPeriod = 5;
        static System.Threading.Timer timer;
        static AutoResetEvent ev;
        static void Main(string[] args) 
        {
            ThreadStart start = new ThreadStart(SomeThreadMethod);
            Thread thr = new Thread(start);
            thr.Name = "background";
            thr.IsBackground = true;
            ev = new AutoResetEvent(false);
            timer = new System.Threading.Timer(
                Timer_TimerCallback, ev, TimeSpan.FromSeconds(TimerPeriod), TimeSpan.Zero);
            thr.Start();
            Console.WriteLine(string.Format("Timer started at {0}", DateTime.Now));
            Console.ReadLine();
        }
    
        static void Timer_TimerCallback(object state) {
            AutoResetEvent ev =  state as AutoResetEvent;
            Console.WriteLine(string.Format
                 ("Timer's callback method is executed at {0}, Thread: ", 
                 new object[] { DateTime.Now, Thread.CurrentThread.Name}));
            ev.Set();
        }
    
        static void SomeThreadMethod() {
            WaitHandle.WaitAll(new WaitHandle[] { ev });
            Console.WriteLine(string.Format("Thread is running at {0}", DateTime.Now));
        }
    }
    

提交回复
热议问题