[英](C# Unity) Stoping timer and showing the stopped time in another scene
[英]Timer cannot be stopped in C#
我在Windows窗体(C#3.0,.net 3.5 SP1,VS2008 SP1,Vista)上有一个计时器,即使该计时器已停止运行,它也似乎可以正常工作。 代码是:
using System;
using System.Windows.Forms;
namespace TestTimer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StartTimer();
}
private DateTime deadline;
private void StartTimer()
{
deadline = DateTime.Now.AddSeconds(4);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
int secondsRemaining = (deadline - DateTime.Now).Seconds;
if (secondsRemaining <= 0)
{
timer1.Stop();
timer1.Enabled = false;
MessageBox.Show("too slow...");
}
else
{
label1.Text = "Remaining: " + secondsRemaining.ToString() + (secondsRemaining > 1 ? " seconds" : " second");
}
}
}
}
即使在调用timer1.Stop()之后,我仍然在屏幕上保留MessageBoxes。 当我按esc时,它停止。 但是,我预计只会出现一个消息框...我该怎么办? 添加timer1.Enabled = false不会更改行为。
谢谢
我可能是错的,但是MessageBox.Show()是阻塞操作(等待您关闭对话框)吗? 如果是这样,只需将Show()调用移至Stop / Enabled行之后?
这里可能有几个因素在起作用。
模态MessageBox.Show()可能会阻止计时器停止生效,直到将其关闭(如Brian指出的那样)。
timer1_Tick可能正在后台线程上执行。 UI调用(例如MessageBox.Show()和后台线程)不能混合使用。
通过使用BeginInvoke调用显示消息框的方法,可以解决这两个问题。
请注意以下是不必要的:
timer1.Stop();
timer1.Enabled = false;
Stop()
与Enabled=false
相同。 并且Start()
与Enabled=true
相同。
http://msdn.microsoft.com/zh-CN/library/system.windows.forms.timer.enabled.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.