c# 跨线程委托操作
控件
button
lable
progressBar

主程序
//更新UI
private void UpdataUIStatus(int step)
{
if (InvokeRequired)
{
this.Invoke(new Action<int>(delegate (int s)//匿名委托
{
// Thread.Sleep(10);
this.progressBar1.Value += s;
this.label1.Text = this.progressBar1.Value.ToString() + "/" + this.progressBar1.Maximum.ToString();
}), step);
}
else
{
this.progressBar1.Value += step;
this.label1.Text = this.progressBar1.Value.ToString() + "/" + this.progressBar1.Maximum.ToString();
}
}
//完成任务时需要调用
private void Accomplish()
{
MessageBox.Show("任务完成");
}
private void button1_Click(object sender, EventArgs e)
{
int taskCount = 10000; //任务量为10000
this.progressBar1.Maximum = taskCount;
this.progressBar1.Value = 0;
DataWrite dataWrite = new DataWrite();//实例化对象
dataWrite.UpdateUIDelegate += UpdataUIStatus;//前面的函数委托后面的函数执行
dataWrite.TaskCallBack += Accomplish;//前面的函数委托后面的函数执行
Thread thread = new Thread(new ParameterizedThreadStart(dataWrite.Write)); //开启新的线程,执行write()函数
thread.IsBackground = true;
thread.Start(taskCount);
}
对象类
public class DataWrite
{
public Action<int> UpdateUIDelegate;//申明一个可以包裹1个int参数函数的委托
public Action TaskCallBack;//申明一个可以包裹1个无返回函数的委托
public void Write(object lineCount)
{
for (int i = 0; i < (int)lineCount; i++)
{
Thread.Sleep(100);
UpdateUIDelegate(1);
}
TaskCallBack();
}
}



浙公网安备 33010602011771号