C# 计时器或 Thread.Sleep [英] C# Timer or Thread.Sleep

查看:29
本文介绍了C# 计时器或 Thread.Sleep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行 Windows 服务并使用循环和 Thread.Sleep 来重复任务,使用计时器方法会更好吗?

I am running a windows service and using a loop and Thread.Sleep to repeat a task, would it be better to use a timer method?

如果是,代码示例会很棒

If yes a code example would be great

我目前正在使用此代码重复

I am currently using this code to repeat

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;
    }
}

代码可能类似于上面的代码

The code could resemble something like the one above

这篇关于C# 计时器或 Thread.Sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆