【问题标题】:c# append text to a rich text box from a thread using a delegatec# 使用委托将文本从线程附加到富文本框
【发布时间】:2018-04-06 22:35:30
【问题描述】:

我想让我的 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 });

        }

【问题讨论】:

    标签: c# multithreading delegates richtextbox


    【解决方案1】:

    我会把它放在你的 Form1 类中

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

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

    【讨论】:

    • 您好 Zach,感谢您提供上述方法。是否有可能我在 MyTcpListener 类中遇到麻烦(线程在 Form1_Load 中启动),因为我正在创建另一个与原始实例无关的 Form1 实例(Form1 form1 = new Form1();)?
    【解决方案2】:

    它现在正在工作。问题是我在 MyTcpListener 类(线程)中创建了一个新的 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);
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 2015-02-15
      • 1970-01-01
      相关资源
      最近更新 更多