2014-10-27 103 views
1

我和我的朋友正在創建一個podcastplayer。每隔30分鐘,60分鐘或2小時,程序應該查看rss feed並查看是否發佈了新劇集。如果是這樣,我們節目中的劇集列表應該隨着新劇集的添加而更新。因此,現在我們試圖使用System.Timers.Timer類來設置執行我們的方法來查找新劇集的時間間隔。爲了測試我們的方法,我們只想每10秒打印出一個消息框。但是在10秒之後,該程序只是不斷髮現新的消息框。我們如何重置計時器並在10秒後顯示一個新的消息框?是因爲我們使用了一個消息框嗎?如果我們除了顯示一個消息框之外還有別的東西,定時器是否會重置?我們嘗試將信息輸出到控制檯,但同樣的問題發生。C#定時器不顯示消息框後重置,只是每秒顯示一個新的消息框

這裏是我們的代碼:

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"); 
} 


} 
+0

不能確定你的問題,但我認爲你需要停止計時器,然後顯示消息框後,再次啓動它,像'timer.Enabled = FALSE;的MessageBox.show( 「你好」); timer.Enabled = true;' – Habib 2014-10-27 14:33:46

回答

3

您可以禁用定時器當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。

System.Timers.Timer在自己的線程上運行,除了UI線程。當時間間隔過去後,它會運行其代碼(在這種情況下,顯示一條消息),然後繼續沿着下一個時間間隔繼續前進。你得到的是大量的消息框,它們都不阻塞UI或其他。

您可以read more here。文章有點舊,但關於不同定時器的信息仍然相關。

0

MessageBox是一個靜態類。 MessageBox.Show()每次都會爲您提供一個新對象。我認爲MessageBoxes也是阻止代碼繼續運行的對話框,這可能會混淆你的計時器。我建議切換到使用其他測試。要驗證您具有所需行爲最簡單的方法是將Console.WriteLine()與測試語句一起使用,並查看Visual Studio中的控制檯/輸出窗口。

或者不使用消息框,而是使用類級作用域創建額外的單個窗體,並顯示和隱藏頁面以指示您的計時器已過期。

參見:http://www.techotopia.com/index.php/Hiding_and_Showing_Forms_in_C_Sharp