随笔 - 47, 评论 - 255, 引用 - 17

导航

工具

关于

我是新人,: )

每月存档

广告



访客

 

我在这里看到的: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:暂无标签

留言反馈

#re: Modify GUI from the worker thread (C#) 编辑
BackgroundWalker这个组件有bug
2006-10-07 15:10:00 | [匿名用户:sunmast]
#re: Modify GUI from the worker thread (C#) 编辑
为什么不用BackGroundWorker来解决呢,它的ReportProcess一样能解决这个问题。
2006-10-06 10:31:00 | [匿名用户:cooltan]
#re: Modify GUI from the worker thread (C#) 编辑
@sunmast: HAHA, yup, I should have mentioned it.
2006-10-05 16:14:00 | [匿名用户:demonfox]
#re: Modify GUI from the worker thread (C#) 编辑
.NET 1.x不一定弹异常,但界面可能很怪
.NET 2.0肯定弹异常
2006-10-05 09:19:00 | [匿名用户:sunmast]
对不起,目前本随笔不允许发表新评论.

Powered by: Joycode MVC Blogger System