gpt4 book ai didi

c# - 从另一个线程和类更新 WinForm 控件

转载 作者:行者123 更新时间:2023-11-30 13:39:21 24 4
gpt4 key购买 nike

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

我四处搜索,找到了针对不同线程和不同类的解决方案,但不是两者都找到了,而且所提供的解决方案似乎不兼容(对我来说)

但这可能是最大的“领先优势”:How to update UI from another thread running in another class

类层次结构示例:

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 允许您在控件自己的线程上执行方法。这也称为异步执行,因为调用实际上是排队并单独执行的。

看看这个article from msdn ,该示例类似于您的示例。单独线程上的单独类更新窗体上的列表框。

-----更新在这里您不必将其作为参数传递。

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

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' 没有被传递。

关于c# - 从另一个线程和类更新 WinForm 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com