c#使用委托

时间:2018-04-06 22:35:30

标签: c# multithreading delegates richtextbox

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

        }

2 个答案:

答案 0 :(得分:0)

我会把它放在你的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方法。

答案 1 :(得分:0)

现在正在运作。问题是我在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);