今天要做一个批量处理图层数据的功能,希望在处理任务过程中,各个任务都能在进度条中显示自己的当前进度,决定继续使用强大易用的BackgroundWorker组件。通过在RunWorkerCompleted事件中进行控制来达到各任务独立显示完成进度的目标。测试在之前的介绍BackgroundWork功能的测试代码基础上展开,测试例子截图如下:
分别向每个ListBox中写入1-100000的数字,向每个Listbox中写入过程中,进度条都自左向右走一遍,直到3个ListBox写入数字任务全部完成。代码如下:
public partial class Form1 : Form
{
List<ListBox> m_NumberBoxList = new List<ListBox>();//存放ListBox
ListBox m_CurrentListBox = null;//当前写入Items的ListBox
int m_CurrentListBoxIndex = ;//当前写入Items的ListBox的索引
public Form1()
{
InitializeComponent(); backgroundWorker1.WorkerReportsProgress = true;//报告完成进度
backgroundWorker1.WorkerSupportsCancellation = true;//允许用户终止后台线程
backgroundWorker1.DoWork += new DoWorkEventHandler(ListNumber); m_NumberBoxList.Add(listBox1);
m_NumberBoxList.Add(listBox2);
m_NumberBoxList.Add(listBox3);
} private void btnOk_Click(object sender, EventArgs e)
{
//向第一个ListBox写入数值
m_CurrentListBox = m_NumberBoxList[];
if (!backgroundWorker1.IsBusy)//判断backgroundWorker1是否正在运行异步操作
{
backgroundWorker1.RunWorkerAsync();//开始执行后台操作
}
} void ListNumber(object sender, DoWorkEventArgs e)
{
int num = (int)e.Argument;//接收传入的参数
for (int i = ; i <= num; i++)
{
if (backgroundWorker1.CancellationPending)//判断是否请求了取消后台操作
{
e.Cancel = true;
return ;
}
backgroundWorker1.ReportProgress(i * / num, i);//报告完成进度
System.Threading.Thread.Sleep();//后台线程交出时间片
}
} private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;//将完成进度数据传给进度条
m_CurrentListBox.Items.Add(e.UserState);//将中间计算结果在ListBox控件中显示出来
m_CurrentListBox.Update();//刷新ListBox
} private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Value = ;
m_CurrentListBoxIndex++; if(m_CurrentListBoxIndex!=m_NumberBoxList.Count)
{
m_CurrentListBox = m_NumberBoxList[m_CurrentListBoxIndex];
if (!backgroundWorker1.IsBusy)//判断backgroundWorker1是否正在运行异步操作
{
backgroundWorker1.RunWorkerAsync();//开始执行后台操作
}
}
else
{
m_CurrentListBoxIndex = ;
MessageBox.Show("处理完成!");
}
} private void btnStop_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();//取消后台操作
backgroundWorker1.Dispose();//释放资源
}
}
}
运行过程截图如下: