C# Timer 一次经过一个实例 [英] C# Timer elapsed one instance at a time

查看:48
本文介绍了C# Timer 一次经过一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建 Windows 服务.我想每 30 秒运行一次服务.

I am creating windows service. I want to run the service every 30 seconds.

所以我在 Windows 服务上使用了计时器,使用以下代码启动.

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();
        }

在 timer1_tick 函数中,我正在执行一些操作,例如更新用户详细信息、上传和下载文件.

In timer1_tick function, I am performing some actions like updating user details, uploading and downloading files.

但在这里我不确定上述操作是否会在 30 秒内完成.所以我想一次运行一个.

But here I am not sure that the above action will finish within 30 seconds. So I want to run one at a time.

此处timer1_tick 函数每精确到 30 秒调用一次.仅当 timer1_tick 函数完成每项任务时,才会发生这种情况.

Here timer1_tick function called every exact 30 seconds. This should be happen only if the timer1_tick function finishes every task.

怎么做?

推荐答案

您应该停止计时器并使用 Timer.Stop(); 等待文件的上传和下载完成>Timer.Start():

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();
}

希望有帮助!

这篇关于C# Timer 一次经过一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆