gpt4 book ai didi

C# 使用委托(delegate)进行跨线程时遇到问题

转载 作者:行者123 更新时间:2023-11-30 12:24:00 25 4
gpt4 key购买 nike

我在使用委托(delegate)从非主窗体线程的线程更改 Textbox 时遇到问题。

我有两个类,一个是带有 UI 的主 Form1.cs 类,另一个是 LINClass.cs,我在其中编写了一个设备函数。在 Form1 中,我启动了一个持续轮询设备的后台工作程序,以及另一个从设备中检索数据的线程 (RXTask()),这两个线程的所有函数都来自 LINCLass.cs。

从设备检索数据的线程包含一个指向允许更改 Form1 文本框的 Form1.cs 函数的委托(delegate):

public class LINClass : Form
{
private delegate void FormUpdater(int devnum, string rpm, string current, string temp);

//some other variables and procedure

public void RXTask()
{
FormUpdater frmUpdt = new FormUpdater(Form1.GUIupdate);
//other procedures and a loop containing the invoke...
this.Invoke(frmUpdt, new object[]{devnum, rpm,
current,
temperature});

}

Form1 类包含调用的方法,如下所示

public static void GUIupdate(int eWPnum, string rpm, string current, string temp)
{
//take the parameters and write them in the textbox
}

现在,当我运行代码时,线程正在运行,但调用函数时出现异常。

http://s13.postimg.org/9ohuj9d7r/exception.png

它说,“未管理 InvalidOperationException,在创建窗口句柄之前无法在控件上调用 Invoke 或 BeginInvoke”

最佳答案

您应该使用命令模式并将命令类从一个线程放入队列中,然后让另一个线程从中读取。

关于C# 使用委托(delegate)进行跨线程时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35086062/

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