这两个System.Timers.Timer和System.Threading.Timer火在离请求的那些相当不同的时间间隔.例如:
new System.Timers.Timer(1000d / 20);
Run Code Online (Sandbox Code Playgroud)
产生一个每秒发射16次而不是20次的计时器.
为了确保太长的事件处理程序没有副作用,我写了这个小测试程序:
int[] frequencies = { 5, 10, 15, 20, 30, 50, 75, 100, 200, 500 };
// Test System.Timers.Timer
foreach (int frequency in frequencies)
{
int count = 0;
// Initialize timer
System.Timers.Timer timer = new System.Timers.Timer(1000d / frequency);
timer.Elapsed += delegate { Interlocked.Increment(ref count); };
// Count for 10 seconds
DateTime start = DateTime.Now;
timer.Enabled = true;
while (DateTime.Now < start + TimeSpan.FromSeconds(10))
Thread.Sleep(10);
timer.Enabled = false;
// Calculate …Run Code Online (Sandbox Code Playgroud) 我需要帮助.我有Windows服务,我需要在特定时间每小时运行一次这项服务,例如:09:05,10:05,11:05,....我的服务现在每小时开始,但从我开始这项服务的每个小时开始.那么我怎样才能实现我的需求呢.
我的代码:
public partial class Service1 : ServiceBase
{
System.Timers.Timer timer = new System.Timers.Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteToFile("Starting Service {0}");
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
this.WriteToFile("Stopping Service {0}");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
this.WriteToFile(" interval start {0}");
} }
Run Code Online (Sandbox Code Playgroud)