我对使用 backgroundWorker 有点陌生,并且一直在网上研究如何使用它。从我得到的例子中,有些东西是没有意义的。在您的 DoWork 函数中,您从 0-100 或 1-10 运行一个循环,该循环基本上会告诉您的进度条您的进度是什么,并且在该循环内您可以完成所有艰苦的工作。那么如果你有一些工作要做,那就是一个循环,例如循环一个列表并将值打印到一个文件中?
这是我一直在玩的代码。
void m_oWorkder_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
taskLabel.Text = "Task Cancelled";
}
else if (e.Error != null)
{
taskLabel.Text = "Error while performing background operation.";
}
else
{
taskLabel.Text = "Task Completed...";
}
startButton.Enabled = true;
cancelButton.Enabled = false;
}
void m_oWorkder_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
taskLabel.Text = "Processing ... " + progressBar1.Value.ToString() + "%";
}
void m_oWorkder_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
someRandom();
m_oWorker.ReportProgress(i);
if (m_oWorker.CancellationPending)
{
e.Cancel = true;
m_oWorker.ReportProgress(0);
return;
}
}
m_oWorker.ReportProgress(100);
}
private void startButton_Click(object sender, EventArgs e)
{
startButton.Enabled = false;
cancelButton.Enabled = true;
m_oWorker.RunWorkerAsync();
}
private void cancelButton_Click(object sender, EventArgs e)
{
if (m_oWorker.IsBusy)
{
m_oWorker.CancelAsync();
}
}
private void someRandom()
{
int x = 0;
while (x != 100)
{
x++;
Console.WriteLine("Value of x = " + x);
}
}