wpf 如何暂停 Threading.timer 以完成功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13266916/
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
How to pause a Threading.timer to complete a function
提问by ar.gorgin
Possible Duplicate:
Synchronizing a timer to prevent overlap
可能的重复:
同步计时器以防止重叠
I have a Threading.Timerin my class.
Threading.Timer我班上有一个。
System.Threading.Timer timer;
TimerCallback cb = new TimerCallback(ProcessTimerEvent);
timer = new Timer(cb, reset, 1000, Convert.ToInt64(this.Interval.TotalSeconds));
and defined a callback for it.
并为它定义了一个回调。
private void ProcessTimerEvent(object obj)
{
if(value)
MyFunction();
}
When run it, re-running callback before myfunctionto complete.
运行它时,重新运行之前的回调才能myfunction完成。
How to pause Threading.Timerto complete myfunction?
如何暂停Threading.Timer完成myfunction?
回答by Ivan Leonenko
It is not necessary to stop timer, 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.
没有必要停止计时器,您可以让计时器继续触发回调方法,但将您的不可重入代码包装在 Monitor.TryEnter/Exit 中。在这种情况下无需停止/重新启动计时器;重叠调用不会获取锁并立即返回。
object lockObject = new object();
private void ProcessTimerEvent(object state)
{
if (Monitor.TryEnter(lockObject))
{
try
{
// Work here
}
finally
{
Monitor.Exit(lockObject);
}
}
}
回答by Adrian Thompson Phillips
You can disable a System.Threading.Timerby changing the interval. You can do this by calling:
您可以System.Threading.Timer通过更改间隔来禁用 a 。您可以通过调用:
timer.Change(Timeout.Infinite, Timeout.Infinite);
You'll have to change the interval back once you have finished calling myfunctionif you want the timer to continue firing again.
myfunction如果您希望计时器再次继续触发,您必须在完成调用后更改间隔。

