1. 新建一个窗体,并隐藏标题栏,拖拽一个ProgressBar进度条控件
2.后台代码实现
1)定义委托,用于更新前端UI
delegate void AsynUpdateUI(int step);
2)在窗体加载事件里面注册委托事件,启动线程
private void FormClient_Load(object sender, EventArgs e)
{
int taskCount = 100;
this.pgbWrite.Maximum = taskCount;
this.pgbWrite.Value = 0;
DataWrite dataWrite = new DataWrite();//实例化一个写入数据的类
dataWrite.UpdateUIDelegate += UpdataUIStatus;//绑定更新任务状态的委托
dataWrite.TaskCallBack += Accomplish;//绑定完成任务要调用的委托
Thread thread = new Thread(new ParameterizedThreadStart(dataWrite.Write));
thread.IsBackground = true;
thread.Start(taskCount);
}
3)创建一个DataWrite类,用于写入数据
internal class DataWrite
{
public delegate void UpdateUI(int step);//声明一个更新主线程的委托
public UpdateUI UpdateUIDelegate;
public delegate void AccomplishTask();//声明一个在完成任务时通知主线程的委托
public AccomplishTask TaskCallBack;
public void Write(object lineCount)
{
for (int i = 0; i < (int)lineCount; i++)
{
//编写要完成事情的代码,目前先用等待代替
Thread.Sleep(50); //等待一下,也可以去掉
//写入一条数据,调用更新主线程ui状态的委托
UpdateUIDelegate(1);
}
//任务完成时通知主线程作出相应的处理
TaskCallBack();
//将更新包信息写入到客户端文件配置中
Thread.Sleep(1000);
Application.Exit();
}
}
4)定义更新前端UI的方法
private void UpdataUIStatus(int step)
{
if (InvokeRequired)
{
this.Invoke(new AsynUpdateUI(delegate (int s)
{
this.pgbWrite.Value += s;
this.lblProcess.Text = "检测到最新程序,正在更新请稍候("+this.pgbWrite.Value.ToString() + "%)...";
}), step);
}
else
{
this.pgbWrite.Value += step;
this.lblProcess.Text = "检测到最新程序,正在更新请稍候(" + this.pgbWrite.Value.ToString() + "%)...";
}
}
5)定义完成任务后要调用的方法
private void Accomplish()
{
//还可以进行其他的一些完任务完成之后的逻辑处理
if (InvokeRequired)
{
this.Invoke(new AsynUpdateUI(delegate (int s)
{
lblProcess.Text = "更新完成,即将启动客户端...";
}), 0);
}
else {
lblProcess.Text = "更新完成,即将启动客户端...";
}
}
以上步骤就以异步方式实现了一个Winform进度条的功能,下面是具体效果截图: