What if a timer can not finish all its works before the new cycle time arrives?

懵懂的女人 提交于 2019-12-18 11:16:46

问题


Suppose we have a timer which runs every 10 minutes. What if the cycle of its processing takes more than 10 minutes. Does a new thread starts for that? Will it interrupt its current operation? What if a single object is mutated inside the timer?

Sorry if I do not mention any code for that because the problem is clear and also I want to know the complete answer from the viewpoint of a multi-threaded programming geek rather than finding a loose answer by trying to test it via a sample application. Actually, I want to know the logic behind its working mechanism.


回答1:


If you're using System.Threading.Timer or System.Timers.Timer, the timer will tick again, starting a new thread. See https://stackoverflow.com/a/10442117/56778 for a way to avoid that problem.

If you're using System.Windows.Forms.Timer, then a new tick won't occur until the previous one is finished processing.




回答2:


Put your code in a Monitor.TryEnter()

object timeCheck= new object();

void Timer()
{
    Monitor.TryEnter(timeCheck) 
    {
        //Code that might take too long 
        //...
        Monitor.Exit();
    }
}



回答3:


to prevent reentrancy, you might use a static boolean that tells wether the function is allready beeing executed. User a try/Catch/finally and set this boolean to false in the finally to ensure that the boolean does not remain false if you made a mistake in code or if the code failed.
For a faster timer, reentrancy should be prevented by using semaphore (mutex).



来源:https://stackoverflow.com/questions/10471315/what-if-a-timer-can-not-finish-all-its-works-before-the-new-cycle-time-arrives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!