gpt4 book ai didi

c# - 如何从另一个表单的线程将文本粘贴到表单的 RichTextBox?

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:26 24 4
gpt4 key购买 nike

我在 C# 中有一个 Windows 窗体应用程序。我在主窗口 (MainForm) 中有一个 RichTextBox(Txt) 和一个公共(public)方法

public void postTxt(String txt)
{
//do some database update
this.Txt.AppendText(txt);
}

我有另一个名为 SerialTranseiver(MainForm mn) 的表单,它作为构造函数中的参数传递给 MainForm。

SerialTranseiver(MainForm mn)
{
//-----other codes
this.tmpMain=mn;
}

第二个类有一个 SerialPort(Sport) 并等待数据,只要在其中找到数据SerialDataReceivedEventHandler 调用 mn.postTxt(Sport.ReadLine().toString())

void Sport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
mn.postTxt(Sport.ReadLine().toString());
//---database updating codes and other stuff
}

这会引发异常

Cross-thread operation not valid: Control 'Txt' accessed from a thread other than the thread it was created on

我该如何解决这个问题?

最佳答案

一种方法是异步调用委托(delegate),该委托(delegate)以您调用它的形式公开。例如:

 mainForm.BeginInvoke(mainForm.logDelegate,destination,fileName,bytesSent, true);

我建议您阅读 this首先和this之后

关于c# - 如何从另一个表单的线程将文本粘贴到表单的 RichTextBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8286476/

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