以下计时器始终从当前日期开始。如何将代码更改为从0:0:0:0开始? 所以不要显示:
Elapsed事件于09:40:31.084提出 Elapsed事件于09:40:33.100提出 Elapsed事件于09:40:35.100提出 ...
它会显示:
Elapsed事件于00:00:01.084筹集 Elapsed事件于00:00:02.084筹集 Elapsed事件于00:00:03.084提出 ...
感谢您的帮助。
using System;
using System.Timers;
public class Example
{
private static System.Timers.Timer aTimer;
public static void Main()
{
SetTimer();
Console.WriteLine("\nPress the Enter key to exit the application...\n");
Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
Console.ReadLine();
aTimer.Stop();
aTimer.Dispose();
Console.WriteLine("Terminating the application...");
}
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
}
答案 0 :(得分:2)
您必须记住开始时间并计算差异以查看花费的时间:
private static DateTime start;
private static void SetTimer()
{
//
// set the start time
//
start = DateTime.Now;
...
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
//
// calculate the time spent
//
TimeSpan spent = DateTime.Now - start;
Console.WriteLine($"The Elapsed event was raised at {spent.Hours}:{spent.Minutes:D2}:{spent.Seconds:D2}:{spent.Milliseconds:D3}");
}