我在这里看到的:http://devdistrict.com/CodeDetails.aspx?A=366,不知道为什么是9/15/2006才提交的文章,应该是很平常的东西了呀。
Anyway,文章很短,我简单地意译了一下:
多线程程序应该避免在一个worker thread里直接改动GUI的内容和对象(注:I believe .NET runtime will now throw an exception if you actually do that.)
Worker thread应该通过以下方式来更新GUI:
public partial class Form1 : Form
...{
private delegate void PrintMessageDelegate(string msg);
![]()
public Form1()
...{
InitializeComponent();
}
![]()
private void button1_Click(object sender, EventArgs e)
...{
//Start new thread
Thread t = new Thread(new ThreadStart(DoWork));
t.Start();
}
![]()
private void DoWork()
...{
//Marshal request to the GUI thread
textBox1.Invoke(new PrintMessageDelegate(PrintMessage), new string[] ...{"Print this!"});
}
![]()
private void PrintMessage(string msg)
...{
lock (this)
...{
textBox1.Text = msg;
}
}
}
在上面的程序中,当你点击按钮时,程序生成了一个新的线程。在这个新的worker线程里,我们想修改TextBox的内容。Worker线程marshals a call to the GUI thread。但GUI进入CPU运行的时候,它就会调用marshal过来的PrintMessage函数了。
打印 | 张贴于 2006-10-05 08:25:00 | Tag:暂无标签




}
}
留言反馈
.NET 2.0肯定弹异常