1. 界面设计

C#上位机开发(十)—— 多线程+进度条的使用_多线程

2. 使用多线程修改进度条

引入多线程类库命名空间:

using System.Threading;

将变量添加到Form1类:

private Thread th;

将方法添加到Form1类:

private void ThreadTask()
{
int stp;
int newval;
Random rnd = new Random();

while (true)
{
stp = this.progressBar1.Step * rnd.Next(-1, 2);
newval = this.progressBar1.Value + stp;
if (newval > this.progressBar1.Maximum)
newval = this.progressBar1.Maximum;
else if (newval < this.progressBar1.Minimum)
newval = this.progressBar1.Minimum;
this.progressBar1.Value = newval;
Thread.Sleep(100);
}
}

在按键回调函数中添加创建线程的代码(设置为后台线程,随程序一起关闭):

private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "开始")
{
button1.Text = "停止";
th = new Thread(new ThreadStart(ThreadTask));
th.IsBackground = true;
th.Start();
}
else
{
th.Abort();
button1.Text = "开始";
}
}

3. 效果

C#上位机开发(十)—— 多线程+进度条的使用_后台线程_02