计时器在C#模式下持续启动,无法停止
有人能帮我停止windows form C3应用程序中的计时器吗?我使用designer在表单中添加了计时器,间隔设置为1000;我想在按钮点击后等待5秒后做一些动作。请检查代码并通知我。现在的问题是,我得到MessageBox2的次数是无限的,而且计时器从未停止计时器在C#模式下持续启动,无法停止,c#,.net,timer,C#,.net,Timer,有人能帮我停止windows form C3应用程序中的计时器吗?我使用designer在表单中添加了计时器,间隔设置为1000;我想在按钮点击后等待5秒后做一些动作。请检查代码并通知我。现在的问题是,我得到MessageBox2的次数是无限的,而且计时器从未停止 static int count; public Form1() { InitializeComponent(); timer1.Tick += timer1_Tic
static int count;
public Form1()
{
InitializeComponent();
timer1.Tick += timer1_Tick;
}
public void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
while(count>5)
{
....dosome actions...
}
}
private void timer1_Tick(object sender, EventArgs e)
{
count1++;
MessageBox.Show("Messagebox2");
if (count1 == 5)
{
//timer1.Enabled = false; timer1.Stop();
((System.Timers.Timer)sender).Enabled = false;
MessageBox.Show("stopping timer");
}
}
我将使
计数
无效,只需使用timer 1 interval
属性,并将您的操作放入timer 1_Tick
事件中
public void button1_Click(object sender, EventArgs e)
{
timer1.Interval = 5000;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
MessageBox.Show("stopping timer");
// Your other actions here
}
您正在递增
count1
并检查count
while(count1 > 5)
{
...dosome actions...
}
你用哪个定时器?因为C#支持来自两个不同名称空间的类计时器。一个来自表单,另一个来自System.Timers。我建议您使用另一个-System.Timers.Timer
Timer t = new Timer(20000); // created with 20seconds
t.Enabled = true; // enables firing Elapsed event
t.Elapsed += (s, e) => {
\\do stuff
};
t.Start();
在这段简短的代码中,您可以看到计时器是如何创建和启用的。通过注册到已过去的事件,您可以明确地说出时间过去后要做什么。这只需要做一次。当然,如果用户在达到限制之前单击按钮,则需要进行一些更改。但这在很大程度上取决于您所要求的行动的行为。count1在哪里?count1属于谁?它也是静态的吗?您是否在某个地方将其设置为0?此代码有很多错误。但是从丢失消息框开始,使用Debug.Print。首先将“发件人”转换为System.Windows.Forms.Timer。提示:打印出值
count1
,看看是否符合您的期望。启动计时器后,单击按钮1\u单击
方法检查count
。如果count
已初始化为小于5的值,则while
循环将不会执行,方法将结束。这闻起来像是需要一个计时器和一个后台工作线程。“我使用designer在表单中添加了计时器,间隔设置为1000”我从工具箱中取出计时器放入表单,这正是System.Windows.Forms命名空间中的计时器。来自System.Timers的那个也会做同样的事情,我认为它更适合使用。