2014-10-27 112 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