Stopping timer in its callback method

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

    I do it with Interlocked that provides atomic operations, and by CompareExchange ensures that only one thread at a time enters the critical section:

    private int syncPoint = 0;
    
    private void Loop()
        {
            int sync = Interlocked.CompareExchange(ref syncPoint, 1, 0);
             //ensures that only one timer set the syncPoint to  1 from 0
            if (sync == 0)
            {
                try
                {
                   ...
                }
                catch (Exception pE)
                {
                   ...  
                }
                syncPoint = 0;
            }
    
        }
    

提交回复
热议问题