【发布时间】:2011-03-31 09:04:39
【问题描述】:
我想要一个具有以下属性的计时器:
-
无论调用多少次start,只有一个回调线程一直在运行
-
关于时间间隔,在回调函数中花费的时间被忽略了。例如,如果间隔为 100 毫秒,并且回调需要 4000 毫秒执行,则在 100 毫秒、4100 毫秒等处调用回调。
我看不到任何可用的内容,因此编写了以下代码。有没有更好的方法来做到这一点?
/**
* Will ensure that only one thread is ever in the callback
*/
public class SingleThreadedTimer : Timer
{
protected static readonly object InstanceLock = new object();
//used to check whether timer has been disposed while in call back
protected bool running = false;
virtual new public void Start()
{
lock (InstanceLock)
{
this.AutoReset = false;
this.Elapsed -= new ElapsedEventHandler(SingleThreadedTimer_Elapsed);
this.Elapsed += new ElapsedEventHandler(SingleThreadedTimer_Elapsed);
this.running = true;
base.Start();
}
}
virtual public void SingleThreadedTimer_Elapsed(object sender, ElapsedEventArgs e)
{
lock (InstanceLock)
{
DoSomethingCool();
//check if stopped while we were waiting for the lock,
//we don't want to restart if this is the case..
if (running)
{
this.Start();
}
}
}
virtual new public void Stop()
{
lock (InstanceLock)
{
running = false;
base.Stop();
}
}
}
【问题讨论】:
标签: c# multithreading timer