[英]stop timer after interval time in c#
我在Visual Studio 2008中使用.net compact framework 3.5
。
我創建了一個計時器滴答事件來執行一項工作。我只想調用一次計時器,然后我需要禁用計時器。請參見下面的代碼
int counter = 0;
var timer = new Timer { Enabled = true, Interval = 10000 };
timer.Tick += delegate
{
Cleanup();
};
counter++;
if (counter >= 1)
{
timer.Enabled = false;
}
我嘗試使用timer.Enabled = false;
在沒有任何條件的情況下,發生的事情是在tick事件中沒有調用Cleanup()
函數。因此,我從Google獲得了另一個使用counter的解決方案。對於counter我也面臨着同樣的問題, Cleanup()
不是打電話。
如果我沒有禁用計時器,則該函數每10秒調用一次。我只需要調用一次Cleanup()
函數,該函數位於timer.tick中。需要幫助解決此問題。
謝謝
為什么需要櫃台:
這樣就足夠了
timer.Tick += delegate
{
timer.Enabled = false;
Cleanup();
};
如果使用的是System.Timers.Timer
則可以使用另一種方法-使用Timer.AutoReset使其僅觸發一次:
var timer = new System.Timers.Timer(10000) { AutoReset = false };
timer.Elapsed += (s,e)=>Cleanup();
timer.Enabled = true;
使用lambda的簡短表示法:
var timer = new Timer { Enabled = true, Interval = 10000 };
timer.Tick +=()=>{ timer.Enabled=false; Cleanup();};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.