2014-09-22 58 views
0

我使用按钮和文本框的形式。 Button正在启动正在更新文本框值的线程。线程更新GUI在随机时刻冻结

public Form1() 
    { 
     InitializeComponent(); 
     myDelegate = new UpdateUi(updateUi); 
    } 
    private void button1_Click(object sender, EventArgs e) 
    { 
     myThread = new Thread(new ThreadStart(ThreadFunction)); 
     myThread.Start(); 
    } 
    private void ThreadFunction() 
    { 
     MyThreadClass myThreadClassObject = new MyThreadClass(this); 
     myThreadClassObject.Run(); 
    } 
    private void updateUi(int i) 
    { 
     textBox1.Text = i.ToString(); 
     Thread.Sleep(1000); 
    } 
    public Thread myThread; 
    public delegate void UpdateUi(int i); 
    public UpdateUi myDelegate; 

和ThreadClass:

public class MyThreadClass 
{ 
    Form1 myFormControl1; 
    public MyThreadClass(Form1 myForm) 
    { 
     myFormControl1 = myForm; 
    } 

    public void Run() 
    { 
     // Execute the specified delegate on the thread that owns 
     // 'myFormControl1' control's underlying window handle. 
     for(int i=0;i<100;i++) 
     { 
      if(myFormControl1.InvokeRequired) 
      { 
       myFormControl1.Invoke(myFormControl1.myDelegate,i); 
      } 

     } 


    } 
} 

正如你可以看到有没有什么特别的,我的代码,但有时代码冻结。

例如它会出现1-> 2-> 3-> freeze-> 16-> 17等等。

我把代码HERE很少修改

+1

示例中的'Thread.Sleep'只是为了减慢速度。你不需要那么简单,只需将它从代码中移除即可。 – 2014-09-22 10:54:26

+0

那么你告诉我'Thread.Sleep'是造成这种奇怪的行为的原因吗? – szpic 2014-09-22 10:59:09

+0

他需要它才能看到'textBox1'中的数字。 – GeorgeChond 2014-09-22 11:00:14

回答

1

的问题是,你正在拖延UI线程不是过程本身,以便发生的事情是你发出的所有更新命令,但因为它在同一个线程它在所有运行因为Thread.Sleep停止UI线程,所以它运行一堆textBox1.Text = i.ToString();然后它停止在所有的Thread.Sleep(1000);所有的时间可能是1-> 2-> 3的数量......你看到的是等于核心数量在你的机器上。

当你停止运行方法时,你会发出一个立即运行的更新命令并等待一秒钟,直到你发出下一个命令,我认为它正在尝试完成。