[英]C# - Winform Timer - Disposing and emptying the timer
C# 和計時器相當新,雖然我已經設法在 C# 中做了一些非常有趣的事情,但是我沒有掌握計時器的竅門。
Form1.cs:
private int counter;
static System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
public void goTimer()
{
// Set Counter
counter = 60;
// If timer is already enabled, stop it.
if (timer1.Enabled)
{
timer1.Dispose();
//timer1.Stop() <- also tried
}
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start(); // Timer exists
txtCountdown.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if(counter == 0)
{
timer1.Stop();
}
txtCountdown.Text = counter.ToString();
}
所以,發生的事情是它似乎按預期工作,直到你開始調用goTimer();
從例如按下按鈕,然后它會加快(int) counter
的速度,就像你按下它的次數一樣......一段時間后,memory 將被吃掉。
在這種情況下,用戶將能夠調用定時器 function,因為它會刪除一些對象,清除一些數據並刷新 session,而且當定時器達到 0 時。
使用 Winforms,我沒有在 Visual Studio 中添加計時器(僅在 Form1.cs 中引用)。
如何終止所有計時器,然后在 (int) counter
處重新啟動?
使用timer
的啟動和停止將是正確的方法,但通常也可以使用 dispose 變體。
您的 memory 孔是由多重事件處理程序分配產生的,您需要將此方法移動到您的構造函數或其他一些初始化方法:
timer1.Tick += new EventHandler(timer1_Tick);
如果你真的想每次都創建一個新的定時器,你需要在之前釋放事件處理程序:
timer1.Tick -= timer1_Tick;
首先,正如 MichaelSander 已經提到的,您應該將這些行放在您的Form1.cs
構造函數中:
timer1.Tick += new EventHandler(timer1_Tick); timer1.Interval = 1000; // 1 second
其次,如果要多次使用計時器,則處置計時器是沒有意義的。 您應該使用timer1.Stop()
而不是timer1.Dispose()
(),就像在timer1_Tick
處理程序中一樣。 此外,檢查計時器是啟用還是禁用也沒有意義,因為timer1.Start()
和timer1.Stop()
將分別打開/關閉它或什么都不做。 這意味着在您的情況下,您可以完全刪除此塊:
if (timer1.Enabled) { timer1.Dispose(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.