可靠地停止 System.Threading.Timer? [英] Reliably stop System.Threading.Timer?
本文介绍了可靠地停止 System.Threading.Timer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗯,我已经搜索了很多解决方案.我正在寻找一种干净简单的方法来防止 System.Threading.Timer 的回调方法在我停止后被调用.
Well I've searched a lot for a solution to this. I'm looking for a clean and simple way to prevent the callback method of a System.Threading.Timer from being invoked after I've stopped it.
我似乎找不到任何东西,这让我有时不得不求助于可怕的 thread-thread.sleep-thread.abort 组合.
I can't seem to find any, and this has led me, on occassion, to resort to the dreaded thread-thread.sleep-thread.abort combo.
可以用锁来实现吗?
推荐答案
like Conrad Frix 建议您应该使用 System.Timers.Timer
类代替,例如:
like Conrad Frix suggested you should use the System.Timers.Timer
class instead, like:
private System.Timers.Timer _timer = new System.Timers.Timer();
private volatile bool _requestStop = false;
public constructor()
{
_timer.Interval = 100;
_timer.Elapsed += OnTimerElapsed;
_timer.AutoReset = false;
_timer.Start();
}
private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// do work....
if (!_requestStop)
{
_timer.Start();//restart the timer
}
}
private void Stop()
{
_requestStop = true;
_timer.Stop();
}
private void Start()
{
_requestStop = false;
_timer.Start();
}
这篇关于可靠地停止 System.Threading.Timer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文