我有一个问题,使用委托从不是主窗体线程的线程更改Textbox
。使用代表进行交叉线程的C#麻烦
我有两个类,一个主要的Form1.cs类与UI和另一个类LINClass.cs,我写了一个设备函数。 在Form1中,我启动了一个连续轮询设备的背景工作器,另一个线程从设备检索数据(RXTask()),两个线程的所有功能都来自LINCLass.cs。
从设备中检索数据的线程包含一个代表指向某Form1.cs的函数,其允许改变Form1中的文本框:
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异常不管理,调用或BeginInvoke可直到窗口句柄已创建不能在控制称为”
这是一个众所周知的问题。你需要谷歌BeginInvoke的规范解决方案。基本上,你必须检查是否需要调用,如果是你使用相同的参数调用它,并停止在错误的线程上执行。 – Carlos
您可能在窗体的'Initialize()'方法运行完成之前调用该方法。如果文本框尚未添加到from的控件集合中,则会出现此错误。 – InBetween
Windows不是实时操作系统;你确定你想尝试轮询设备**连续**吗?你是否愿意加热整个CPU,除此之外什么都不做?我的笔记本电脑的电池寿命不会感谢你。为什么不在一个线程上做所有事情,并且不是同时处理设备? –