C# Timer elapsed one instance at a time

2019-09-08 10:35发布

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?

2条回答
我命由我不由天
2楼-- · 2019-09-08 10:51

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!

查看更多
甜甜的少女心
3楼-- · 2019-09-08 11:01

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.
}
查看更多
登录 后发表回答