Stopping timer in its callback method

前端 未结 5 937
逝去的感伤
逝去的感伤 2020-12-05 01:23

I have a System.Threading.Timer that calls its appropriate event handler (callback) every 10 ms. The method itself is not reentrant and can

5条回答
  •  盖世英雄少女心
    2020-12-05 01:38

    I've had similar situation with a System.Timers.Timer, where the elapsed event is executed from a threadpool and needs to be reentrant.

    I used this method to get around the issue:

    private void tmr_Elapsed(object sender, EventArgs e)
    {
        tmr.Enabled = false;
        // Do Stuff
        tmr.Enabled = true;
    }
    

    Depending on what you're doing you may want to consider a System.Timers.Timer, here's a nice summary from MSDN

                                             System.Windows.Forms    System.Timers         System.Threading  
    Timer event runs on what thread?         UI thread               UI or worker thread   Worker thread
    Instances are thread safe?               No                      Yes                   No
    Familiar/intuitive object model?         Yes                     Yes                   No
    Requires Windows Forms?                  Yes                     No                    No
    Metronome-quality beat?                  No                      Yes*                  Yes*
    Timer event supports state object?       No                      No                    Yes
    Initial timer event can be scheduled?    No                      No                    Yes
    Class supports inheritance?              Yes                     Yes                   No
    
    * Depending on the availability of system resources (for example, worker threads)            
    

提交回复
热议问题