在c#中每x秒执行一次操作,持续y分钟 [英] Execute an operation every x seconds for y minutes in c#

查看:42
本文介绍了在c#中每x秒执行一次操作,持续y分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要每 5 秒运行一次函数,持续 10 分钟.

I need to run a function every 5 seconds for 10 minutes.

我使用计时器运行 5 秒,但如何将计时器限制为仅 10 分钟?

I use a timer to run it for 5 secs, but how do I limit the timer to only 10 mins?

推荐答案

只需在经过处理的处理程序中捕获您想要停止和结束计时器的时间即可.这是一个示例(注意:我使用了 System.Threading.Timer timer.为您正在做的事情选择合适的计时器.例如,您可能在 System.Windows.Forms.Timer(如果您使用 Winforms 编写.)

Just capture the time that you want to stop and end your timer from within the elapsed handler. Here's an example (note: I used a System.Threading.Timer timer. Select the appropriate timer for what you are doing. For example, you might be after a System.Windows.Forms.Timer if you are writing in Winforms.)

public class MyClass
{
    System.Threading.Timer Timer;
    System.DateTime StopTime;
    public void Run()
    {
        StopTime = System.DateTime.Now.AddMinutes(10);
        Timer = new System.Threading.Timer(TimerCallback, null, 0, 5000);
    }

    private void TimerCallback(object state)
    {
        if(System.DateTime.Now >= StopTime)
        {
            Timer.Dispose();
            return;
        }
        // Do your work...
    }
}

这篇关于在c#中每x秒执行一次操作,持续y分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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