按钮挂起无限循环

时间:2016-08-20 01:02:56

标签: c# winforms global-variables infinite-loop cycle

如果我启动我的C#Windows窗体应用程序,按钮会挂起,因为它是无限循环。我想通过全局变量

看到button2的变量值变化为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;
        }
    }
}

2 个答案:

答案 0 :(得分:-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
    }

答案 1 :(得分:-1)

查看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;
    }
}