如何解决交叉线程操作在Windows窗体中无效?

时间:2013-03-07 12:45:10

标签: c# asp.net .net ado.net tcpclient

我一直被困在这里.....我正在创建一个聊天服务器Windows应用程序,它将托管并且所有客户端都将注册

让我解释一下我的场景,当我启动聊天服务器时......我使用了TextBox名称ChatTextBox,其中我尝试获取所有注册的客户端IP地址

但是当我尝试在服务器上注册一个客户端时,显示跨线程操作无效,如何解决呢????

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Threading;

namespace Myservercheck
{
public partial class Form2 : Form
{
    TcpListener myli;
    TcpClient clientSocket = default(TcpClient);
    string s=string.Empty;

    public Form2(TcpListener tc)
    {
        myli = tc;
        InitializeComponent();

    }

    private void Form2_Load(object sender, EventArgs e)
    {
        IPlistBox.Items.Add(myli.LocalEndpoint.ToString());
        chattextBox.Text= "Chat server started on selected IP & Port Number:\n"+myli.LocalEndpoint.ToString();
        chattextBox.AppendText("\n");
        chattextBox.AppendText("Waiting for connections............\n");
        myli.Start();
       Thread thread1 = new Thread(listern);
       thread1.Start();
        chattextBox.AppendText("\n");


    }


    public void listern()
    {
        while (true)
        {

            clientSocket = myli.AcceptTcpClient();
            IPAddress tempAddress = ((IPEndPoint)(clientSocket.Client.RemoteEndPoint)).Address;
            chattextBox.Text = tempAddress.ToString();
            chattextBox.AppendText("Connection accepted from:" + s);
        }
        }
    }




    }

1 个答案:

答案 0 :(得分:1)

您需要在窗体控件上调用一个方法来委托窗体的线程。您只能从创建表单的同一线程访问表单控件。

public void listern() {
    while (true) {
        clientSocket = myli.AcceptTcpClient;
        IPAddress tempAddress = ((IPEndPoint)(clientSocket.Client.RemoteEndPoint)).Address;
        UpdateChattextBox(tempAddress.ToString, "Connection accepted from:" + s);     
    }
}

public void UpdateChattextBox(string address, string message) {
    if ((chattextBox.InvokeRequired == true)) {
        this.invoke(UpdateCattextBox, address, message);
    }
    else {
        chattextBox.Text = tempAddress.ToString;
        chattextBox.AppendText(("Connection accepted from:" + s));
    }
}