问题
I am creating windows service. I want to run the service every 30 seconds.
So I have used timer on windows service start using the following code.
protected override void OnStart(string[] args)
{
timer1 = new Timer();
timer1.Interval = 30000;
timer1.Elapsed += new ElapsedEventHandler(timer1_tick);
timer1.Start();
}
In timer1_tick function, I am performing some actions like updating user details, uploading and downloading files.
But here I am not sure that the above action will finish within 30 seconds. So I want to run one at a time.
Here timer1_tick function called every exact 30 seconds. This should be happen only if the timer1_tick function finishes every task.
How to do that?
回答1:
You should stop the timer and wait for the uploading and downloading of files to finish using Timer.Stop();
and Timer.Start()
:
void timer1_tick(...){
timer1.Stop();
//Do your download, upload, etc.
timer1.Start();
}
Hope it helps!
回答2:
As per your requirement use Asynchronous Programming. It might be help you. Thank You
timer1.Elapsed += new ElapsedEventHandler(await timer1_tick);
async Task<void> timer1_tick()
{
//Do your download, upload, etc.
}
来源:https://stackoverflow.com/questions/43221178/c-sharp-timer-elapsed-one-instance-at-a-time