Stopping timer in its callback method

前端 未结 5 940
逝去的感伤
逝去的感伤 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:29

    You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately.

     private void CreatorLoop(object state) 
     {
       if (Monitor.TryEnter(lockObject))
       {
         try
         {
           // Work here
         }
         finally
         {
           Monitor.Exit(lockObject);
         }
       }
     }
    

提交回复
热议问题