我正在运行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
}
}
最佳答案
class Program
{
static void Main(string[] args)
{
Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000);
Console.Read();
timer.Dispose();
}
public static void TimeCallBack(object o)
{
curMinute = DateTime.Now.Minute;
if (lastMinute < curMinute) {
// do your once-per-minute code here
lastMinute = curMinute;
}
}
该代码可能类似于上面的代码
关于c# - C#计时器或Thread.Sleep,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1091710/