我正在创建一个程序,其中一部分需要连接到工作sql服务器,检索活动客户帐户列表,然后将该列表显示到组合框中。代码执行在初始加载表单期间应该执行的操作,但是当我尝试从刷新按钮运行后台工作程序时,我收到一条错误消息:
此BackgroundWorker当前正忙,无法同时运行多个任务
我很困惑为什么在我看来,代码显然已经到了RunWorkerCompleted方法的末尾。
private void EnterCompletions_Load(object sender, EventArgs e)
{
lblcomboBox1Status.Text = "Attempting to download list of active accounts ...";
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// *** tblaccts - AID | AName ***
myConnection.Open();
SqlCommand myCommand = new SqlCommand("SELECT AID, AName " +
"FROM tblaccts " +
"WHERE Status IS NULL " +
"ORDER BY AID ASC", myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
accts_aid.Add(myReader["AID"].ToString());
accts_aname.Add(myReader["AName"].ToString());
}
myConnection.Close();
for (int i = 0; i < accts_aid.Count; i++) // create a list which contains strings in this format: "account number | account name"
{
accts_string_aid.Add(accts_aid[i] + " | " + accts_aname[i]);
}
for (int i = 0; i < accts_aname.Count; i++) // create a list which contains strings in this format: "account name | account number"
{
accts_string_name.Add(accts_aname[i] + " | " + accts_aid[i]);
}
accts_aid.Clear();
accts_aname.Clear();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error == null)
{
if(rbAid.Checked)
{
foreach (string stuff in accts_string_aid) // fill the combobox with the custom display format: "account number | account name"
{
comboBox1.Items.Add(stuff);
}
aid_or_name = "aid";
}
if(rbName.Checked)
{
foreach (string stuff in accts_string_name) // fill the combobox with the custom display format: "account name | account number"
{
comboBox1.Items.Add(stuff);
}
aid_or_name = "name";
}
lblcomboBox1Status.Text = "Account list successfully downloaded.";
comboBox1.Focus();
comboBox1.DroppedDown = true;
}
else
{
lblcomboBox1Status.Text = "Unable to connect to the server.";
}
}