System.Timers.Timer/Threading.Timer vs Thread with WhileLoop + Thread.Sleep For Periodic Tasks

前端 未结 4 1157
悲&欢浪女
悲&欢浪女 2020-12-02 11:23

In my application I have to send periodic heartbeats to a \"brother\" application.

Is this better accomplished with System.Timers.Timer/Threading.Timer or Using a Th

4条回答
  •  佛祖请我去吃肉
    2020-12-02 11:42

    Neither :)

    Sleeping is typically frowned upon (unfortunately I cannot remember the particulars, but for one, it is an uninteruptible "block"), and Timers come with a lot of baggage. If possible, I would recommend System.Threading.AutoResetEvent as such

    // initially set to a "non-signaled" state, ie will block
    // if inspected
    private readonly AutoResetEvent _isStopping = new AutoResetEvent (false);
    
    public void Process()
    {
        TimeSpan waitInterval = TimeSpan.FromMilliseconds (1000);
    
        // will block for 'waitInterval', unless another thread,
        // say a thread requesting termination, wakes you up. if
        // no one signals you, WaitOne returns false, otherwise
        // if someone signals WaitOne returns true
        for (; !_isStopping.WaitOne (waitInterval); )
        {
            // do your thang!
        }
    }
    

    Using an AutoResetEvent (or its cousin ManualResetEvent) guarantees a true block with thread safe signalling (for such things as graceful termination above). At worst, it is a better alternative to Sleep

    Hope this helps :)

提交回复
热议问题