简体   繁体   English

C#计时器一次经过一个实例

[英]C# Timer elapsed one instance at a time

I am creating windows service. 我正在创建Windows服务。 I want to run the service every 30 seconds. 我想每30秒运行一次服务。

So I have used timer on windows service start using the following code. 所以我在Windows服务上使用计时器使用以下代码启动。

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. 在timer1_tick函数中,我正在执行一些操作,例如更新用户详细信息,上载和下载文件。

But here I am not sure that the above action will finish within 30 seconds. 但是在这里我不确定上述动作是否会在30秒内完成。 So I want to run one at a time. 所以我想一次运行一次。

Here timer1_tick function called every exact 30 seconds. 在这里, timer1_tick函数每隔30秒调用一次。 This should be happen only if the timer1_tick function finishes every task. 仅当timer1_tick函数完成每个任务时,才应该发生这种情况。

How to do that? 怎么做?

You should stop the timer and wait for the uploading and downloading of files to finish using Timer.Stop(); 您应该停止计时器,并等待使用Timer.Stop();完成文件的上传和下载Timer.Stop(); and Timer.Start() : Timer.Start()

void timer1_tick(...){
    timer1.Stop();
    //Do your download, upload, etc.
    timer1.Start();
}

Hope it helps! 希望能帮助到你!

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM