在用c#做WinFrom开发的过程中。我们经常需要用到进度条(ProgressBar)用于显示进度信息。这时候我们可能就需要用到多线程,如果不采用多线程控制进度条,窗口很容易假死(无法适时看到进度信息)。下面我就简单结合一个我写的例子给大家做一个介绍。 第一步:设计界面不说了...注意需要引用 using System.Threading; //更新进度列表 private delegate void SetPos(int ipos); 第三步:进度条值更新函数(参数必须跟声明的代理参数一样) private void SetTextMessage(int ipos) { if (this.InvokeRequired) { SetPos setpos = new SetPos(SetTextMessage); this.Invoke(setpos, newobject[] { ipos}); } else { this.label1.Text = ipos.ToString() + "/100"; this.progressBar1.Value = Convert.ToInt32(ipos); } } 第四步:函数实现 privatevoid button1_Click(object sender, EventArgs e) { Thread fThread = new Thread(new ThreadStart(SleepT));//开辟一个新的线程 fThread.Start(); } 第五步:新的线程执行函数: privatevoid SleepT() { for (int i = 0; i < 500; i++) { System.Threading.Thread.Sleep(100);//没什么意思,单纯的执行延时 SetTextMessage(100 * i / 500); } } |
=============================
使用浮动进度条
1.浮动窗口
/// <summary>
/// Increase process bar
/// </summary>
/// <param name="nValue">the value increased</param>
/// <returns></returns>
public bool Increase(int nValue)
{
if (nValue > 0)
{
if (prcBar.Value + nValue < prcBar.Maximum)
{
prcBar.Value += nValue;
return true;
}
else
{
prcBar.Value = prcBar.Maximum;
this.Close();
return false;
}
}
return false;
}
2.使用进度的窗口
using System.Threading;
private frmProcessBar myProcessBar = null;
private delegate bool IncreaseHandle(int nValue);
private IncreaseHandle myIncrease = null;
private void ShowProcessBar()
{
myProcessBar = new frmProcessBar();
// Init increase event
myIncrease = new IncreaseHandle(myProcessBar.Increase);
myProcessBar.StartPosition = FormStartPosition.CenterScreen;
myProcessBar.ShowDialog();
myProcessBar = null;
}
private void ThreadFun()
{
MethodInvoker mi = new MethodInvoker(ShowProcessBar);
this.BeginInvoke(mi);
Thread.Sleep(1000);//Sleep a while to show window
bool blnIncreased = false;
object objReturn = null;
do
{
Thread.Sleep(50);
objReturn = this.Invoke(this.myIncrease, new object[] { 2 });
blnIncreased = (bool)objReturn;
}
while (blnIncreased);
}
使用方法:
Thread thdSub = new Thread(new ThreadStart(ThreadFun));
thdSub.Start();