从另一个线程_and_类更新WinForm控件

我正在制作一个WinForms程序,它需要单独的线程为了可读性和可维护性,我将所有非GUI代码分离到不同的类中。 这个类还“生成”另一个类,它进行一些处理。 但是,我现在遇到的问题是我需要从一个在另一个类中启动的线程更改WinForms控件(将字符串附加到文本框)

我已经四处搜索,并找到了不同线程的解决方案,并且在不同的类中,但不是两者,并且所提供的解决方案似乎不兼容(对我而言)

这可能是最大的“领先”: 如何从另一个类中运行的另一个线程更新UI

类层次结构示例:

class WinForm : Form { ... Server serv = new Server(); } // Server is in a different thread to winform class Server { ... ClientConnection = new ClientConnection(); } // Another new thread is created to run this class class ClientConnection { //Want to modify winform from here } 

我知道事件处理程序可能是要走的路,但我不知道如何在这种情况下这样做(我也对其他建议开放;))

任何帮助赞赏

从哪个类更新表单无关紧要。 WinForm控件必须在创建它们的同一个线程上更新。

因此,Control.Invoke允许您在自己的线程上对控件执行方法。 这也称为异步执行,因为调用实际上是排队并单独执行的。

从msdn看这篇文章 ,这个例子类似于你的例子。 单独线程上的单独类更新表单上的列表框。

—–更新您不必将此作为参数传递。

在Winform类中,有一个可以更新控件的公共委托。

 class WinForm : Form { public delegate void updateTextBoxDelegate(String textBoxString); // delegate type public updateTextBoxDelegate updateTextBox; // delegate object void updateTextBox1(string str ) { textBox1.Text = str1; } // this method is invoked public WinForm() { ... updateTextBox = new updateTextBoxDelegate( updateTextBox1 ); // initialize delegate object ... Server serv = new Server(); } 

从ClientConnection对象,您必须获得对WinForm:Form对象的引用。

 class ClientConnection { ... void display( string strItem ) // can be called in a different thread from clientConnection object { Form1.Invoke( Form1.updateTextBox, strItem ); // updates textbox1 on winForm } } 

在上述情况下,’this’未通过。

你可以使用backgroundworker制作你的其他线程,它可以让你轻松处理你的GUI

http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx