日期:2014-05-19  浏览次数:20929 次

在窗体中启动一个线程进行循环运算时,如何动态改变窗体中一个Label的值,使之等于运算结果
问题如上.解决问题即结贴.谢谢兄弟们的帮助.谢谢

------解决方案--------------------
可以设置一个Timer 隔一定时间更新一次 也可以使用事件 计算一定量触发更新UI的事件
------解决方案--------------------
namespace WindowsApplication_学习_多线程
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
System.Threading.Thread thread = new System.Threading.Thread(Thread_Calc);
thread.IsBackground = true;
thread.Start();
}
private void Thread_Calc()
{
for (int i = 0; i < 100; i++)
{
label1.Text = i.ToString();
System.Threading.Thread.Sleep(100);
}
//this.EndInvoke(null);
}
}
}
------解决方案--------------------
private SortedList sl = null;
2 private const int TEST_COUNT = 10000;
3 private void button1_Click(object sender, System.EventArgs e)
4 {
5 mi = new MethodInvoker(DoWork);
6 mi.BeginInvoke(new AsyncCallback(DoneWork), null);
7 }
8 private void DoWork()
9 {
10 sl = new SortedList();
11 InitialPB(TEST_COUNT);
12 for (int i =0;i <TEST_COUNT;i++)
13 {
14 sl.Add(i, "NoWay " + i.ToString());
15 Thread.Sleep(100);
16 RefreshText( "NoWay " + i.ToString());
17 RefreshPB(1);
18 }
19
20 }
21 private void InitialPB(int max)
22 {
23 if( InvokeRequired )
24 {
25 this.Invoke( new IntDelegate(InitialPB), new object [] { max } );
26 return ;
27 }
28 progressBar1.Maximum = max ;
29 progressBar1.Value = 0;
30 }
31 private void RefreshText(string item)
32 {
33 if( InvokeRequired )
34 {
35 this.Invoke( new StringDelegate(RefreshText), new object [] { item } );
36 return ;
37 }
38 this.textBox1.Text = item;
39 }
40 private void RefreshPB(int Value)
41 {
42 if( InvokeRequired )
43 {
44 this.Invoke( new IntDelegate(RefreshPB), new object [] {Value} );
45 return ;
46 }
47 progressBar1.Value+=Value;
48 }
49 private void DoneWork(IAsyncResult result)
50 {
51 if( InvokeRequired )
52 {
53 Invoke(new AsyncCallback(DoneWork), new Object [] { result } );
54 return ;
55 }
56 MessageBox.Show( "Done! ")
57;
58 }
59 private void button2_Click(object sender, System.EventArgs e)
60 {
61 mi.EndInvoke(null);
62 }
63 private MethodInvoker mi= null;
64 private delegate void IntDelegate(int num);
65 private delegate void StringDelegate(string str);

------解决方案--------------------
可以考虑用事件的方式,运算的时候触发事件,把运算结果作为参数传递,在主线程中挂载事件并更新label的显示。