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

标签 c# multithreading

我在 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/

相关文章:

c# - 从 WinForms 应用程序使用 UrlDecode

c# - 关于异步返回类型

java - 如何在java中使 'modified' ArrayList线程安全?

c - 使用 pthread 让一个线程执行其他线程发送的所有磁盘写入操作?

c# - ASP.NET MVC 和 C# : HttpStatusCodeResult() vs HttpNotFound()

c# - 通过 C# 复制 pdf 注释

c# - 从多个线程异步写入文件c#

Pythonic 线程安全对象

.net - 在特定时间段内阻塞线程的精确方法是什么?

c# - 如何将图像控件绑定(bind)到以 VarBinary 类型保存在数据库中的图像