progressBar+线程举例(winform,c#)

来源:互联网 发布:遗传算法的基本流程图 编辑:程序博客网 时间:2024/06/05 04:48

int count = 1000;  //测试总数
/// <summary>
/// 方法1
/// </summary>
private void setthread()
{
this.progressBar1.Minimum = 0;
this.progressBar1.Value = 0;
this.progressBar1.Maximum = count;
for (int i = 0; i < count; i++)
{
this.progressBar1.Value++;
Application.DoEvents();
this.label2.Text = "总数"+count.ToString()+",剩余数量:" +Convert.ToString(count-i-1);
}
}
/// <summary>
/// 方法2
/// </summary>
private void setthread2()
{
this.progressBar1.Minimum = 0;
this.progressBar1.Value = 0;
this.progressBar1.Maximum = count;
for (int i = 0; i < count; i++)
{
this.progressBar1.Value++;
this.label2.Text = "总数" + count.ToString() + ",剩余数量:" +Convert.ToString(count - i - 1);
this.label2.Refresh();
}
}
/// <summary>
/// 方法3,线程
/// </summary>
private void setthread3()
{
for (int i = 0; i < count; i++)
{
string tmptext = "总数" + count.ToString() + ",剩余数量:" +Convert.ToString(count - i - 1);
this.Invoke(new setLabel(setLabel2), tmptext);
this.Invoke(new setProgressBar(setProgressBar1),1);
}
}
private void button1_Click(object sender, EventArgs e)
{
setthread();
}
private void button2_Click(object sender, EventArgs e)
{
setthread2();
}
System.Threading.Thread thread;
private void button3_Click(object sender, EventArgs e)
{
this.progressBar1.Minimum = 0;
this.progressBar1.Value = 0;
this.progressBar1.Maximum = count;
System.Threading.Thread.CurrentThread.IsBackground = true;
thread = new System.Threading.Thread(newSystem.Threading.ThreadStart(setthread3));
thread.Start();
}
public delegate void setLabel(string text);
public delegate void setProgressBar(int value);
private void setLabel2(string text)
{
this.label2.Text = text;
}
private void setProgressBar1(int value)
{
this.progressBar1.Value = this.progressBar1.Value+value;
}

----------------------------------------------------------------------------------------------

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;

 
private bool flag=false;
 
private System.Threading.Thread timerThread;
 
private int a=0;

privatevoid StopThread()
{
if (timerThread != null)
{
  timerThread.Interrupt();
  timerThread
= null;
}
}
publicvoid ThreadProc()
{

for (inti = 0; i< 10000;i++)
{
 
for(int j= 0; j< 10000;j++) ;
  a
=a + i;
}
flag
=true;

}
privatevoid progress_Load(object sender,System.EventArgs e)
{
this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = 10000;
}
privatevoid button1_Click(object sender,System.EventArgs e)
{
StopThread();
timerThread
=new Thread(new ThreadStart(ThreadProc));
timerThread.IsBackground
= true;
timerThread.Start();
while (flag == false)
{
 
while(this.progressBar1.Value < this.progressBar1.Maximum)
  
this.progressBar1.Value += 1;
 
if(progressBar1.Value== progressBar1.Maximum)
  
this.progressBar1.Value = 0;
}
Form1 frm1
=new Form1(a.ToString());
frm1.Show();
}
}

0 0
原创粉丝点击