【发布时间】:2019-10-12 13:36:38
【问题描述】:
我遇到了一个问题,我希望能够修改另一个类的文本框。
我尝试过搜索和测试解决方案,但似乎没有一个能胜任。 (调用一个例子..)
cThread 类的代码:
class cThread
{
public bool closed = false;
private TcpClient client;
private StreamReader ins;
private StreamWriter ots;
Form1 meow = new Form1();
public cThread(TcpClient client, StreamReader ins, StreamWriter ots)
{
this.client = client;
this.ins = ins;
this.ots = ots;
}
public void run()
{
try
{
string responseLine;
responseLine = meow.bunifuCustomTextbox2.Text;
while ((responseLine = ins.ReadLine()) != null)
{
Console.WriteLine(responseLine);
meow.bunifuCustomTextbox3.Text = responseLine + " test";
if (responseLine.IndexOf("*** Adios") != -1)
{
break;
}
}
closed = true;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
Environment.Exit(0);
}
}
这会导致错误:Cross-Thread operation not valid: accessed from a thread other than the thread it was created on.
我也试过这个解决方案:
public void run()
{
try
{
string responseLine;
meow.bunifuCustomTextbox2.Invoke(new MethodInvoker(delegate { responseLine = meow.bunifuCustomTextbox2.Text; }));
while ((responseLine = ins.ReadLine()) != null)
{
Console.WriteLine(responseLine);
meow.bunifuCustomTextbox3.Invoke(new MethodInvoker(delegate { meow.bunifuCustomTextbox3.Text = meow.bunifuCustomTextbox2.Text; }));
meow.bunifuCustomTextbox3.Text = responseLine + " test";
if (responseLine.IndexOf("*** Adios") != -1)
{
break;
}
}
closed = true;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
Environment.Exit(0);
}
}
这也不起作用。同样的错误。
我期望发生的是,当用户在 bunifuCustomTextbox2 中输入消息时,它将被设置为我希望由 bunifuCustomTextbox3 更新的 responseLine。
因为这将是一个多人聊天,我正在将此代码从控制台应用程序转换为 winforms..
对不起,我是个笨蛋:(
【问题讨论】: