日期:2014-05-17  浏览次数:20935 次

C#线程内访问线程外数据
是一个winform小程序。主要功能是:

1、在窗体运行前新建线程,在线程内开启socket服务。
2、当有新的连接时,在主窗口的一个textbox中打印相关信息。

主要问题:在线程内的数据无法在textbox中打印出来。

提示:“线程间操作无效: 从不是创建控件“textBox1”的线程访问它”

源代码:
namespace Server_2
{
    public partial class Form1 : Form
    {
        Thread aThread = null;
        private delegate void FlushClient(string s); //代理
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text += ("正在开启server服务" + "\n" + ".......请稍候..." + "\n");
            aThread = new Thread(new ThreadStart(StartSocketServer));
            aThread.IsBackground = true;
            aThread.Start();
            textBox1.Text += ("server is start!" + "\n");
        }
        public void StartSocketServer()
        {

            IPAddress ip = IPAddress.Parse("192.168.168.163");
            //IP地址跟端口的组合
            IPEndPoint iep = new IPEndPoint(ip, 8001);
            //创建Socket
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定Socket
            socket.Bind(iep);
            //服务器已经做好接收任何连接的准备
            socket.Listen(10);
            while (true)
            {
                //执行accept方法
                Socket Client = socket.Accept();
                byte[] message = new byte[1024];
                NetworkStream networkStream = new NetworkStream(Client);
                int len = networkStr