// 界面的控件button , label, progressBar, statusStrip中的toolStripProgressBar
public Form1()
{
InitializeComponent();
}
long number = 0;
DateTime beginDate; //记时
DateTime endDate;
private void button1_Click(object sender, EventArgs e)
{
beginDate = DateTime.Now;// 记录当前时间
number = 0;
this.label1.Text = "label1";
this.progressBar1.Value = 0;
this.button1.Enabled = false;
Thread thread = new Thread(new ThreadStart(myFun));
thread.Name = "thread1";
thread.IsBackground = true;
thread.Start();
}
// 耗时操作
private void myFun()
{
for (int i = 0; i < 100000000; i++)
{
number += i;
}
if (this.InvokeRequired)//进行判断
{
this.BeginInvoke(new Test(this.sum)); //显示到界面上
}
else
{
sum();
}
}
delegate
delegate void Test();
private void sum()
{
endDate = DateTime.Now;
System.TimeSpan timeSpan = endDate - beginDate;
progressBar1.Maximum = timeSpan.Milliseconds;
toolStripProgressBar1.Maximum = timeSpan.Milliseconds;
for (int i = 0; i <= timeSpan.Milliseconds; i++)
{
progressBar1.Value = i;
toolStripProgressBar1.Value = i;
Application.DoEvents();
}
this.label1.Text = number.ToString();
this.button1.Enabled = true;
}
网友评论