这是我后台工作的DoWor功能,是否考虑到GUI操作的执行情况好吗?后台工作人员执行
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string query = "SELECT * FROM dbo.Liguanea_Lane2";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string scode = dr.GetString(dr.GetOrdinal("code"));
comboBox2.Invoke((MethodInvoker)delegate
{
comboBox2.Items.Add(scode);
});
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
这是调用它的功能:
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox4.SelectedIndex == 0)
{
backgroundWorker1.RunWorkerAsync();
}
else
{
MessageBox.Show("This table doesn't exist within the database");
}
}
目前没有happens..the代码只是在屏幕上的默认形式运行。不加载值,我做错了什么?
我想你会做你的代码工作通过调用'backgroundWorker1.RunWorkerAsync();'直接使用一个按钮。但是你的背景工作者是无用的,因为你在'DoWork'事件中做了一个沉重的UI任务。 –
但我认为使用方法调用者会帮助 – Jevon
不,它不会帮助。当你使用'Invoke'时,你传递给它的动作将在UI线程中运行。 –