设备进入睡眠状态后C#定时器是否继续计数?

时间:2015-01-26 07:33:52

标签: c# windows service timer

我已经使用c#创建了一个Windows服务,需要添加一个定时器,在此期间服务将处于空闲状态,并且应该在此空闲超时发生后才开始处理。

如果设备进入休眠状态,定时器是否会重新开始或是否会继续?

1 个答案:

答案 0 :(得分:0)

做了一点体操并确定了一个我认为是可行的解决方案的解决方案



using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int maxtimeout = 100; // max timeout is 100 seconds, when it reaches this break

            var prevtime = ((DateTime.Now - DateTime.MinValue).TotalMilliseconds) / 1000;

            Console.WriteLine("current time = {0} seconds", prevtime);

            for (; ; )
            {

                Thread.Sleep(5000);
                var newtime = ((DateTime.Now - DateTime.MinValue).TotalMilliseconds) / 1000;
                var timeelapsed = newtime - prevtime;
                Console.WriteLine("Time elapsed = {0}", timeelapsed);
                if (timeelapsed >= maxtimeout)
                {
                    Console.WriteLine("Max timeout reached");
                    break;
                }
                else
                {
                    Console.WriteLine("Max timeout no reached elapased time = {0}", timeelapsed);
                }

            }
        }
    }
}