C# 如果一个计时器不能在新的周期时间到来之前完成它的所有工作怎么办?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10471315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:59:27  来源:igfitidea点击:

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

c#multithreadingtimer

提问by Farshid

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?

假设我们有一个每 10 分钟运行一次的计时器。如果它的处理周期超过 10 分钟怎么办。是否会为此启动一个新线程?它会中断当前的操作吗?如果单个对象在计时器内发生变异怎么办?

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.

抱歉,如果我没有提及任何代码,因为问题很清楚,而且我想从多线程编程极客的角度知道完整的答案,而不是通过尝试通过示例应用程序进行测试来找到松散的答案。其实我想知道它的工作机制背后的逻辑。

采纳答案by Jim Mischel

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

如果您使用System.Threading.TimerSystem.Timers.Timer,计时器将再次滴答滴答,开始一个新线程。有关避免该问题的方法,请参阅https://stackoverflow.com/a/10442117/56778

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

如果您正在使用System.Windows.Forms.Timer,则在前一个标记完成处理之前不会发生新的标记。

回答by GameAlchemist

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).

为了防止重入,您可以使用一个静态布尔值来告诉函数是否已经被执行。使用 try/Catch/finally 并在 finally 中将此布尔值设置为 false 以确保如果您在代码中犯了错误或代码失败,布尔值不会保持为 false。
对于更快的计时器,应通过使用信号量(互斥量)来防止重入。

回答by rare

Put your code in a Monitor.TryEnter()

把你的代码放在一个 Monitor.TryEnter()

object timeCheck= new object();

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