[英]C# Timer not resetting after displaying a messagebox, just displaying a new messagebox every second
我和我的朋友正在創建一個播客播放器。 每30分鍾,60分鍾或2小時,該程序應查看rss提要並查看是否已發布新劇集。 如果是這樣,我們的節目中的劇集列表應該在添加新劇集時刷新。
所以,現在我們嘗試使用System.Timers.Timer類來設置執行我們的方法以查找新劇集的間隔。 要測試我們的方法,我們只想每10秒打印一個消息框。 但是在10秒之后,程序就會不斷發布新的消息框。 我們如何重置計時器並在10秒后只顯示一個新的消息框? 是因為我們正在使用消息框嗎? 如果我們除了顯示消息框之外還做其他事情,定時器是否會重置? 我們嘗試將信息打印到控制台,但出現了同樣的問題。
這是我們的代碼:
using System;
using System.Timers;
using System.Windows.Forms;
using Timer = System.Timers.Timer;
public static class TimerInitializer
{
public static Timer timer; // From System.Timers
public static void Start()
{
timer = new Timer(10000); // Set up the timer for 10 seconds
//
// Type "_timer.Elapsed += " and press tab twice.
//
timer.Elapsed += new ElapsedEventHandler(timerElapsed);
timer.Enabled = true; // Enable it
}
public static void timerElapsed(object sender, ElapsedEventArgs e)
{
MessageBox.Show("Hello");
}
}
您可以在Timer.Elapsed
事件觸發時禁用計時器,顯示消息,然后在用戶解除MessageBox
時重新啟用計時器:
public static void timerElapsed(object sender, ElapsedEventArgs e)
{
timer.Stop(); // stop the timer
MessageBox.Show("Hello");
timer.Start(); // restart it; you'll get another msg in 10 seconds
}
通常,使用MessageBox.Show
阻止UI線程,您會注意到在顯示消息時無法單擊UI。
除UI線程外, System.Timers.Timer
在其自己的線程上運行。 當間隔過去時,它運行其代碼(在這種情況下,顯示一條消息),然后只是繼續前進,直到下一個間隔再次過去。 你得到的是很多消息框,沒有一個阻止UI或彼此。
你可以在這里閱讀更多 。 這篇文章有點舊,但有關不同計時器的信息仍然相關。
MessageBox是一個靜態類。 MessageBox.Show()每次都為您提供一個新對象。 我認為MessageBoxes也是阻止代碼繼續運行的對話框,這可能會使你的計時器崩潰。 我建議切換到使用其他東西進行測試。 驗證您具有所需行為的最簡單方法是將Console.WriteLine()與test語句一起使用,並查看Visual Studio中的Console / Output窗口。
或者,不使用消息框而是創建具有類級別范圍的附加單個表單,並顯示和隱藏頁面以指示您的計時器已過期。
請參閱: http : //www.techotopia.com/index.php/Hiding_and_Showing_Forms_in_C_Sharp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.