从火中的OnStart窗口服务立即timer_elapsed [英] Fire timer_elapsed immediately from OnStart in windows service
问题描述
我使用的是 System.Timers.Timer
和我有一样在我的的OnStart
方法在C#中的窗口服务
I'm using a System.Timers.Timer
and I've got code like the following in my OnStart
method in a c# windows service.
timer = new Timer();
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
timer.Interval = 3600000;
timer.Start();
这会导致 timer_Elapsed
中的代码是执行的每一个小时一个小时后,开始我启动该服务。有没有办法让在我启动该服务,然后每隔一小时以后它的点执行?
This causes the code in timer_Elapsed
to be executed every hour starting from an hour after I start the service. Is there any way to get it to execute at the point at which I start the service and then every hour subsequently?
按 timer_Elapsed
调用的方法需要很长时间才能运行,直接从的OnStart叫它
。
The method called by timer_Elapsed
takes too long to run to call it directly from OnStart
.
推荐答案
刚开始一个线程池线程调用函数的工人一样,定时器一样。像这样的:
Just start a threadpool thread to call the worker function, just like Timer does. Like this:
timer.Elapsed += timer_Elapsed;
ThreadPool.QueueUserWorkItem((_) => DoWork());
...
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
DoWork();
}
void DoWork() {
// etc...
}
这篇关于从火中的OnStart窗口服务立即timer_elapsed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!