我定期使用 Threading.Timer 在 Windows 服务中运行一个线程,如下所示:
private Timer _timer;
public void Start()
{
_timer = new Timer(MainLoop, null, 0, Timeout.Infinite);
}
private void MainLoop(object state)
{
// Do something and then tell Timer to wait for a second
_timer.Change(1000, Timeout.Infinite);
}
public void Stop()
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
}
我的问题是我希望 Windows 服务能够监视运行循环的线程,并在发现它已停止时执行一些操作。
以前我使用的是 Thread.Sleep 而不是 Timer,这意味着一切都在单个线程中运行,而不是线程池中的单个线程,我可以查询线程的 ThreadState。现在我正在使用 Timer,ThreadState 为“已停止”,因为一旦 Timer 启动,Thread 就会停止。
那么在使用 Threading.Timer 时确认线程仍在运行的最佳方法是什么?
最佳答案
您可以在内容 MainLoop
周围添加一个 try-finally block ,以确保计时器始终重新启动。
private void MainLoop(object state)
{
try
{
// Do something and then tell Timer to wait for a second
}
finally
{
_timer.Change(1000, Timeout.Infinite);
}
}
如果您仍然认为需要监视此方法的执行,您可以跟踪该方法的上次启动时间。
private void MainLoop(object state)
{
_lastRunTime = DateTime.UtcNow;
try
{
// Do something and then tell Timer to wait for a second
}
finally
{
_timer.Change(1000, Timeout.Infinite);
}
}
然后您可以使用 _lastRunTime
并将其与当前时间进行比较,以查看 MainLoop
的执行是否挂起或计时器(出于某种不明原因)没有重启。
关于c# - 检查控制计时器的线程的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6679505/