Lor*_*Aro 3 c# controls multithreading class winforms
我正在制作一个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
}
Run Code Online (Sandbox Code Playgroud)
我知道事件处理程序可能是要走的路,但在这种情况下我无法弄清楚如何这样做(我也愿意接受其他建议;))
任何帮助赞赏
shr*_*shr 11
从哪个类更新表单无关紧要.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();
}
Run Code Online (Sandbox Code Playgroud)
从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
}
}
Run Code Online (Sandbox Code Playgroud)
在上述情况下,'this'未通过.