Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何准确设置时间段_C#_Timer - Fatal编程技术网

C# 如何准确设置时间段

C# 如何准确设置时间段,c#,timer,C#,Timer,如果我用线,就这样睡觉 while (true) { File.AppendAllText(strCurrentPath + @"\TimerLog.txt", "begin " + DateTime.Now.ToString() + "\r\n"); //do some work which will spent time spendTime(); Thread.Sleep(600000);

如果我用线,就这样睡觉

    while (true)
    {

        File.AppendAllText(strCurrentPath + @"\TimerLog.txt", "begin " + DateTime.Now.ToString() + "\r\n");

        //do some work which will spent time
        spendTime();

        Thread.Sleep(600000);               // sleep  10 mins

    } // while
例如,首先它输出

begin 2014/1/28 12:02:46 
若线程在10分钟后完全唤醒,那个么下一个输出将是

begin 2014/1/28 12:12:46 
但是,因为函数spendTime()将花费一些时间,所以实际输出可能会

begin 2014/1/28 12:13:10
我需要的是,无论花费多少时间,线程都会在10分钟后完全唤醒,请告诉我如何完成它

while (true)
{
    startTime = Environment.TickCount
    File.AppendAllText(strCurrentPath + @"\TimerLog.txt", "begin " + DateTime.Now.ToString() + "\r\n");

    //do some work which will spent time
    spendTime();

    timeBeforeSleep = Environment.TickCount
    consumedTime = timeBeforeSleep - startTime
    Thread.Sleep(600000 - consumedTime);               // sleep  10 mins

} // while
然而,如果这段时间比你的时间间隔长,你应该设法处理它。我不知道你想做什么,但你可以这样跳过睡眠:

if(consumedTime < 600000 )
    Thread.Sleep(600000 - consumedTime);               // sleep  10 mins
if(消费时间<600000)
线程睡眠(600000-消耗时间);//睡10分钟

使用计时器而不是线程。Sleep()

顺便说一句,这听起来像是Windows服务的工作。这样你就不用担心程序退出了

例如,如果您使用的是控制台应用程序,则可以将System.Threading.Timer与TimerCallback一起使用:

using System.Threading;
...

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting");

        var timer = new Timer(TimerCallBack, null, 0, 60000); // change 60000 to 6000 for faster testing!
        Console.ReadLine();
    }

    static void TimerCallBack(object o)
    {
        spendTime();
    }

    static void spendTime()
    {
        Console.WriteLine("spent time" + DateTime.Now.ToString());
        return;
    }
}
在任何一种情况下,间隔都会随着时间的流逝而立即重置,因此您的日志记录将是准确的(至少精确到第二秒)

using System.Threading;
...

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting");

        var timer = new Timer(TimerCallBack, null, 0, 60000); // change 60000 to 6000 for faster testing!
        Console.ReadLine();
    }

    static void TimerCallBack(object o)
    {
        spendTime();
    }

    static void spendTime()
    {
        Console.WriteLine("spent time" + DateTime.Now.ToString());
        return;
    }
}