为什么会冻结

本文关键字:冻结 为什么 | 更新日期: 2023-09-27 17:57:24

我的目标是使我的按钮灵活,具体取决于组合框的当前值,但问题是当我在该特定事件上运行程序时,它会冻结,我的语法有问题还是我的电脑很慢?

private void cmbOperation_SelectedIndexChanged(object sender, EventArgs e)
{
    string selected = (string)cmbOperation.SelectedItem;
    while (selected == "ADD")
    {
        txtID.ReadOnly = true;
        txtLName.ReadOnly = false;
        txtFName.ReadOnly = false;
        txtMI.ReadOnly = false;
        txtGender.ReadOnly = false;
        txtAge.ReadOnly = false;
        txtContact.ReadOnly = false;
        btnOperate.Text = "ADD CLIENT";
    }
}
private void btnOperation_Clicked(object sender, EventArgs e)
{            
    if (cmbOperation.SelectedItem.Equals("ADD"))
    {
        string constring = "datasource=localhost;port3306;username=root";
        string Query = "insert into mybusiness.client_list (LastName,FirstName,MI,Gender,Age,Contact) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtMI.Text + "','" + this.txtGender.Text + "','" + this.txtAge.Text + "','" + txtContact.Text + "' ;";
        MySqlConnection conDB = new MySqlConnection(constring);
        MySqlCommand cmDB = new MySqlCommand(Query, conDB);
        MySqlDataReader myReader;
        try
        {
            conDB.Open();
            myReader = cmDB.ExecuteReader();
                MessageBox.Show("Client Information has been added to the list");
            while(myReader.Read())
            {
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }          
    }
}

为什么会冻结

你没有改变while循环的条件 - 所以如果它是真的,它将永远是真的:

string selected = (string)cmbOperation.SelectedItem;
while (selected == "ADD")
{
    // Code that doesn't change the value of selected
}

但是,您的代码还有其他重大问题:

  • 您正在 UI 线程上执行数据库操作。这将挂起 UI,直到操作完成。最好使用 async/await 和异步数据库操作
  • 你的代码容易受到 SQL 注入攻击,因为你是从值生成 SQL,而不是使用参数化 SQL。请先解决此问题。
  • 您正在调用ExecuteReader来执行插入操作。请改用ExecuteNonQuery - ExecuteReader 专为查询而设计,并且代码不会查询任何内容。
  • 您应该对连接和命令使用 using 语句,以便在执行离开 using 语句的作用域时自动关闭它们 - 当前您的连接将一直挂起,直到它被完成并被垃圾回收;这可能会导致挂起。

while (selected == "ADD")是一个永无止境的无限循环。我想你的意思是:

if(selected == "ADD")

作为旁注。由于这是一个插入查询,我想你需要:

cmDB.ExecuteNoneQuery();

而不是:

myReader = cmDB.ExecuteReader();
MessageBox.Show("Client Information has been added to the list");
while(myReader.Read())
{
}