所以这就是代码:
void scrape()
{
int i = 1;
......
backgroundWorker1.ReportProgress(i);
i = i+1;
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
scrape();
}
void Button1Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
问题是,如果我点击botton1没有任何反应,如果我只是在button1上使用scrape(),它就可以正常工作了。为什么后台工作人员不执行刮擦并使进度条工作?
谢谢!
答案 0 :(得分:0)
在scrape()
方法中,您如何使用变量i
?要使它工作i
应该通过循环递增,如下所示:
void scrape()
{
for (int i = 1; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
}
}
我可以确认上面的代码对我有用。然后不要忘记连接所需的事件和属性:
backgroundWorker1.WorkerReportsProgress = true; //Report a progress
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.DoWork += BackgroundWorker1DoWork; //The scrape
定义:
void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
scrape();
}
答案 1 :(得分:0)
在程序的Initialization / Constructor中,您需要添加这些行以使其正常工作
BackgroundWorker1.DoWork += new BackgroundWorkerDoWorkEventHandler(BackgroundWorker1DoWork)
同样地,它也会转到代码的其他部分
BackgroundWorker1.ProgressChanged += new ProgressChangedEventHandler (backgroundWorker1_ProgressChanged);
BackgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
BackgroundWorker1.WorkerReportsProgress = true;
BackgroundWorker1.WorkerSupportsCancellation = true;