当执行了下属代码后进度条能够正常运行,label1.text并没有根据x值的变化连续变化
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DateTime dt;
int x = 0;
int y = 0;
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
x = 0;
Thread myThread = new Thread(DoData);
Thread myThread1 = new Thread(Viewlabel);
myThread.IsBackground = true;
myThread1.IsBackground = true;
myThread1.Start(int.Parse(textBox1.Text));
myThread.Start(int.Parse(textBox1.Text));
dt = DateTime.Now;
}
private delegate void ViewlabelDelegate(object number);
private void Viewlabel(object number)
{
int i = 1, sum = 0;
if (label1.InvokeRequired)
{
ViewlabelDelegate v = Viewlabel;
label1.Invoke(v, number);
}
else
{
bool flag = true;
while (flag)
{
flag = y < (int)number;
sum += i++;
label1.Text = sum.ToString();
Application.DoEvents();
}
MessageBox.Show(sum.ToString());
}
}
private delegate void DoDataDelegate(object number);
/// <summary>
/// 进行循环
/// </summary>
/// <param name="number"></param>
private void DoData(object number)
{
if (progressBar1.InvokeRequired)
{
DoDataDelegate d = DoData;
progressBar1.Invoke(d, number);
}
else
{
progressBar1.Maximum = (int)number;
bool flag = true;
while (flag)
{
flag = x < (int)number;
progressBar1.Value = x;
Application.DoEvents();
}
MessageBox.Show(DateTime.Now.Subtract(dt).ToString()); //循环结束截止时间
}
}
private void timer1_Tick(object sender, EventArgs e)
{
x = x + 1;
y = y + 1;
}
}
}
当把Viewlabel代码改为下面代码后sum正常计数
[C#] 纯文本查看 复制代码 private void Viewlabel(object number)
{
int i = 1, sum = 0;
while (x < (int)number)
{
sum += i++;
Application.DoEvents();
}
MessageBox.Show(sum.ToString());
}
|