它完成后运行如何停止计时器? [英] How to stop a timer after it is done running?

查看:905
本文介绍了它完成后运行如何停止计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序,并在主要方法,我有这样的代码:

I have a Console App and in the main method, I have code like this:

Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(time_Elapsed);



我只希望计时器运行一次,所以我的想法是,我应该在TIME_ELAPSED停止计时器方法。然而,由于我的定时器在main()存在,我不能访问它。

I only want the timer to run once so my idea is that I should stop the timer in the time_Elapsed method. However, since my timer exists in Main(), I can't access it.

推荐答案

您可以访问内部定时器在 timer_Elapsed 方法:

You have access to the Timer inside of the timer_Elapsed method:

public void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Timer timer = (Timer)sender; // Get the timer that fired the event
    timer.Stop(); // Stop the timer that fired the event
}



以上方法将停止任何计时器计时触发事件(如果你有使用相同处理器的多个计时器,并希望每个定时器具有相同的行为)。

The above method will stop whatever Timer fired the Event (in case you have multiple Timers using the same handler and you want each Timer to have the same behavior).

您也可以设置行为,当你实例定时:

You could also set the behavior when you instantiate the Timer:

var timer = new Timer();
timer.AutoReset = false; // Don't reset the timer after the first fire

这篇关于它完成后运行如何停止计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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