我在backgroundworker上执行了一个非常长的代码,但是有时候我们遇到网络问题而且它显示了webexception,为了处理它我想在异常块中再次调用该函数,我尝试在同一个后台工作器上再次调用函数取消它,但似乎我做得不对,
请检查我的代码,它真的很长,所以我只是在这里发布必要的细节,如果不够,请提前对不起 (在这种情况下让我知道)
public static DataSet ds_input;
private void btn_process_Click(object sender, EventArgs e)
{
//some code here to fetch data and call backgroundworker
backgroundWorker1.RunWorkerAsync(ds);
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
//ds_input is a dataset with data in it
e.Result = check_number(ds_input);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
int i = e.ProgressPercentage;
int j = showProgress(i, Total_Record);
lbl_counter.Text = "Processing " + Convert.ToString(i + 1) + " / " + Convert.ToString(Total_Record) + " ";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
DataTable dt = e.Result as DataTable;
Grid_records.DataSource = e.Result;
}
public void check_number(DataSet ds)
{
try
{
// logic here to perform execution
//sometime it break due to internet connectivity
// i want to resume it in catch block
}
catch (System.Net.WebException ex)
{
//how to run backgroundWorker1 here again
// i did this
backgroundWorker1.CancelAsync();
backgroundWorker1.Dispose();
backgroundWorker1.RunWorkerAsync(ds_input);
// but it says -This BackgroundWorker is currently busy and cannot run multiple tasks concurrently.
//how to resume the function on same backgroundWorker1
}
finally
{
}
}
}
答案 0 :(得分:1)
我会以不需要重新运行后台工作程序的方式调整执行逻辑,而是在结果不符合预期的情况下重新运行操作。也许是这样的:
public static DataSet ds_input;
private void btn_process_Click(object sender, EventArgs e)
{
//some code here to fetch data and call backgroundworker
backgroundWorker1.RunWorkerAsync(ds);
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
bool success = false;
do
{
try
{
e.Result = check_number(ds_input);
success = true;
}
catch (System.Net.WebException ex)
{
success = false;
}
}while(!success);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
int i = e.ProgressPercentage;
int j = showProgress(i, Total_Record);
lbl_counter.Text = "Processing " + Convert.ToString(i + 1) + " / " + Convert.ToString(Total_Record) + " ";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
DataTable dt = e.Result as DataTable;
Grid_records.DataSource = e.Result;
}
public DataTable check_number(DataSet ds)
{
// Do whatever is needed
}
}