[英]stop timer after interval time in c#
I am using .net compact framework 3.5
in visual studio 2008. 我在Visual Studio 2008中使用.net compact framework 3.5
。
I have created a timer tick event to perform a job.I want to call the timer only once and after that i need to disable the timer.Please see my below code 我创建了一个计时器滴答事件来执行一项工作。我只想调用一次计时器,然后我需要禁用计时器。请参见下面的代码
int counter = 0;
var timer = new Timer { Enabled = true, Interval = 10000 };
timer.Tick += delegate
{
Cleanup();
};
counter++;
if (counter >= 1)
{
timer.Enabled = false;
}
I tried with timer.Enabled = false;
我尝试使用timer.Enabled = false;
without any condition,what happens is the Cleanup()
function is not calling which is inside the tick event.So from google i got one more solution to use a counter.With counter also i am facing the same problem, Cleanup()
is not calling. 在没有任何条件的情况下,发生的事情是在tick事件中没有调用Cleanup()
函数。因此,我从Google获得了另一个使用counter的解决方案。对于counter我也面临着同样的问题, Cleanup()
不是打电话。
If i am not disable the timer,then the function is calling in every 10secs time.I need to call the Cleanup()
function only once,which is inside the timer.tick.Need help to solve this. 如果我没有禁用计时器,则该函数每10秒调用一次。我只需要调用一次Cleanup()
函数,该函数位于timer.tick中。需要帮助解决此问题。
Thanks 谢谢
Why do you need a counter: 为什么需要柜台:
This should be enough 这样就足够了
timer.Tick += delegate
{
timer.Enabled = false;
Cleanup();
};
Another approach if you are using System.Timers.Timer
- use Timer.AutoReset to make it fire only once: 如果使用的是System.Timers.Timer
则可以使用另一种方法-使用Timer.AutoReset使其仅触发一次:
var timer = new System.Timers.Timer(10000) { AutoReset = false };
timer.Elapsed += (s,e)=>Cleanup();
timer.Enabled = true;
Short notation using lambda: 使用lambda的简短表示法:
var timer = new Timer { Enabled = true, Interval = 10000 };
timer.Tick +=()=>{ timer.Enabled=false; Cleanup();};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.