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很少修改
示例中的'Thread.Sleep'只是为了减慢速度。你不需要那么简单,只需将它从代码中移除即可。 – 2014-09-22 10:54:26
那么你告诉我'Thread.Sleep'是造成这种奇怪的行为的原因吗? – szpic 2014-09-22 10:59:09
他需要它才能看到'textBox1'中的数字。 – GeorgeChond 2014-09-22 11:00:14