我正在运行一个 Windows 服务,并使用循环和 Thread.Sleep 来重复执行一个任务,是否更好地使用定时器方法?
如果是,提供一个代码示例将会很好。
我目前正在使用以下代码进行重复:
int curMinute;
int lastMinute = DateTime.Now.AddMinutes(-1).Minute;
while (condition)
{
curMinute = DateTime.Now.Minute;
if (lastMinute < curMinute) {
// do your once-per-minute code here
lastMinute = curMinute;
}
Thread.Sleep(50000); // sleeps for 50 seconds
if (error condition that would break you out of this) {
break; // leaves looping structure
}
}