如果单击两次启动后台工作程序的按钮,则会出现此错误。
此BackgroundWorker当前很忙,无法同时运行多个任务
更新记录时如何使它起作用?
这是我的代码
using (SqlConnection con = new SqlConnection("****"))
{
con.Open();
using (SqlCommand com = new SqlCommand("UPDATE indebtedness SET collected=@collected,Payment_Date=@Payment_Date,Payment_Date2=@Payment_Date2 WHERE Subscriber_No=@Subscriber_No and company_name=@company_name and indebtedness_name=@indebtedness_name ", con))
{
com.Parameters.AddWithValue("@company_name", company_name.Text);
com.Parameters.AddWithValue("@indebtedness_name", indebtedness_name.Text);
com.Parameters.AddWithValue("@Payment_Date2", DateTime.Today.ToString());
com.Parameters.Add("@Payment_Date", SqlDbType.Date);
com.Parameters.Add("@Subscriber_No", SqlDbType.BigInt);
com.Parameters.Add(new SqlParameter("@collected", SqlDbType.Decimal) { Precision = 18, Scale = 3 });
int countSuccess = 0;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
com.Parameters["@Subscriber_No"].Value = Convert.ToInt64(dataGridView1.Rows[i].Cells[0].Value);
com.Parameters["@collected"].Value = Convert.ToDecimal(dataGridView1.Rows[i].Cells[1].Value);
com.Parameters["@Payment_Date"].Value = (dataGridView1.Rows[i].Cells[2].Value); //hope this is a date, not a string. If it's a string, parse it instead
int numUpd = com.ExecuteNonQuery();
countSuccess += numUpd;
}
backgroundWorker1.RunWorkerAsync();
progressBar1.Show();
MessageBox.Show($"Successfully UPDATED {countSuccess} of {dataGridView1.Rows.Count} rows");
}
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for(int i=1; i<=dataGridView1.Rows.Count; i++)
{
Thread.Sleep(10);
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.ReportProgress(i);
}
}
private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label6.Text = e.ProgressPercentage.ToString() + "%";
if(label6.Text=="100%")
{
label7.Text = "Record UPdated Successfully .. ";
}
}
我尝试更新记录并在工作时显示结果是小节
代码看起来像这样:
namespace ConsoleApplication1
{
public class State
{
public List<string> data { get; set; }
}
public class MyBackgroundWorker
{
public static BackgroundWorker backgroundWorker1 = new BackgroundWorker();
public void Test()
{
State state = new State();
state.data = new List<string> { "Some Data" };
int progress = 50;
backgroundWorker1.ReportProgress(progress, state);
}
}
class Program
{
static void Main(string[] args)
{
}
private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
State state = e.UserState as State;
//add code to write to datatable here
}
}
}