private delegate void DelegateWriteResult(string file, bool result);
// 与定义的委托签名相同的函数,操作主线程控件
private void WriteResult(string fileName, bool result)
{
if (result)
{
ListViewItem thisListItem = new ListViewItem();
thisListItem.ForeColor = Color.White;
thisListItem.BackColor = Color.DarkGreen;
thisListItem.SubItems[0].Text = fileName;
thisListItem.SubItems.Add("成功");
lvResultList.Items.Add(thisListItem);
}
else
{
ListViewItem thisListItem = new ListViewItem();
thisListItem.ForeColor = Color.White;
thisListItem.BackColor = Color.Red;
thisListItem.SubItems[0].Text = fileName;
thisListItem.SubItems.Add("失败");
lvResultList.Items.Add(thisListItem);
}
}
// 启动线程
// 线程执行函数
private void CompressAll()
{
// 判断是否需要Invoke,多线程时需要
if (this.InvokeRequired)
{
// 通过委托调用写主线程控件的程序,传递参数放在object数组中
this.Invoke(new DelegateWriteResult(WriteResult),new object[] { "item", true });
}
else
{
// 如果不需要委托调用,则直接调用
this.WriteResult("item", true);
}
}
private void button1_Click_1(object sender, EventArgs e)
{
Thread workThread = new Thread(new ThreadStart(CompressAll));
// 设置为背景线程,主线程一旦推出,该线程也不等待而立即结束
workThread.IsBackground = true;
workThread.Start();
}