c# 使用委托将文本从线程追加到富文本框

c# append text to a rich text box from a thread using a delegate

我想让我的 TcpListen 线程使用委托更新 Form1 中的富文本框。 TcpListen 线程正在工作并通过控制台进行通信。但是,我无法在 Form1 中获取富文本框来追加文本。

public class MyTcpListener
{
    public void Server()
    {
        // Some code that produces a string named data
        SendText(data)
    }

    public delegate void TextDelegate(string message);

    public void SendText(string message)
    {
        //Not sure how to send the string to Form1 without removing void and using return string?
    }

public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {
        MyTcpListener listen = new MyTcpListener();
        tserv = new Thread(listen.Server);
        //tserv.IsBackground = true;
        tserv.Start();

        //Where would I call the DisplayText method?
    }
    public void DisplayText(string message)
    {
        if (richTextBox1.InvokeRequired)
        {
            richTextBox1.Invoke(new MyTcpListener.CallBackDelegate(DisplayText),
            new object[] { message });

        }

我会把它放在你的 Form1 中 class

public void AppendTextBox(string value)
{
    if (InvokeRequired)
    {
        this.Invoke(new Action<string>(AppendTextBox), new object[] {value});
        return;
    }
    richTextBox1.AppendText(value);
}

然后将Form1的实例传递给TCPListener的构造函数,当需要更新Form时,调用Form实例的AppendTextBox方法

它正在运行。问题是我在 MyTcpListener class(线程)中创建了 Form1 的新实例,而不是引用原始 Form1。谢谢!

public class MyTcpListener
    {
        private Form1 form1;

        public MyTcpListener(Form1 form1)
        {
        this.form1 = form1;
        }

public partial class Form1 : Form
    { // Some code ...

    private void Form1_Load(object sender, EventArgs e)
    {
        //Start the thread ....
        //Originally I never instantiated an instance of MyTcpListener class
        MyTcpListener mytcplistener = new MyTcpListener(this);