按钮以无限循环悬挂
本文关键字:无限循环 按钮 | 更新日期: 2023-09-27 18:03:08
如果我启动我的c# Windows窗体应用程序,按钮挂起,因为它是无止境的循环。我想看到从button2 click到button1通过全局变量
的无限循环的变量值的变化using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace XX_5
{
public partial class Form1 : Form
{
private int g;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
for (;;)
{
textBox1.AppendText("ID: [" + i++ + "] Variable value: [" + g + "]'n");
}
}
private void button2_Click(object sender, EventArgs e)
{
g = 1;
}
}
}
如果你在按钮点击事件处理程序中保持无限循环,你的应用程序肯定会挂起,因为windows再也不能获取/调度/处理消息了。
可以这样修改:
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
textBox1.AppendText("ID: [" + i++ + "] Variable value: [" + g + "]'n");
}
private void button2_Click(object sender, EventArgs e)
{
// int g = 1; // here you declare a local variable
g = 1; // use the member variable instead
}
看一下Timer控件(在工具箱的Components选项卡下)。你可以把你的代码(没有for循环)放在那里,它将每x毫秒运行一次,这样它就不会挂起。在执行此操作时,需要在表单级别定义i变量。你的计时器可以访问这个"全局变量"。
像这样…
public partial class Form1 : Form
{
private int i = 0;
private int g = 0;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
g = 1;
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.AppendText("ID: [" + i++ + "] Variable value: [" + g + "]'n");
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
}
}