标题:请问新建线程为何不能访问主窗口控件
只看楼主
wuyanmin
Rank: 1
等 级:新手上路
帖 子:10
专家分:1
注 册:2010-5-29
得分:0 
改成这样成么?

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                myIP = IPAddress.Parse(textBox1.Text);
            }
            catch
            {
                MessageBox.Show("IP地址格式错误,请重新输入!");
            }
            try
            {
                Thread thread = new Thread(new ThreadStart(accp));
                thread.Start();
                //accp();
            }
            catch (Exception ee)
            {
                textBox3.AppendText(ee.Message);
            }
        }

        public delegate void MyInvoke();
        
        private void accp()
        {
            MyInvoke mi = new MyInvoke(showServerMessage);
            BeginInvoke(mi);
        }

        public void showServerMessage()
        {
            myServer = new IPEndPoint(myIP, Int32.Parse(textBox2.Text));
            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Bind(myServer);
            sock.Listen(50);
            textBox3.AppendText("主机" + textBox1.Text + "端口" + textBox2.Text + "开始监听... ... \r\n");
            accSock = sock.Accept();
            if (accSock.Connected)
            {
                textBox3.AppendText("与客户建立联系");
                while (check)
                {
                    Byte[] Rec = new Byte[64];
                    NetworkStream netStream = new NetworkStream(accSock);
                    netStream.Read(Rec, 0, Rec.Length);
                    string RecMessage = System.Text.Encoding.BigEndianUnicode.GetString(Rec);
                    richTextBox1.AppendText(RecMessage + "\r\n");
                }
            }
        }

还是有错误啊!
2011-04-19 00:29
Jian_X
Rank: 4
等 级:业余侠客
威 望:1
帖 子:51
专家分:212
注 册:2009-10-23
得分:2 
将Form.CheckForIllegalCrossThreadCalls = false;放在下面位置就可以了。
        public Form1()
        {
            InitializeComponent();
            Form.CheckForIllegalCrossThreadCalls = false;
        }
2011-04-21 10:17
zhp223
Rank: 5Rank: 5
等 级:职业侠客
帖 子:99
专家分:362
注 册:2010-3-21
得分:0 
回复 9楼 qubo1982
这里关键是要解决“错误的线程”怎样运行正确,而不是解决忽略错误提示。
在不是创建该控件的线程上访问该控件,代码就有错,“解决代码的错误”和“让程序忽略这个错误”,你说选哪个呀。

[ 本帖最后由 zhp223 于 2011-4-24 17:48 编辑 ]

日有所思,夜有所梦
2011-04-24 17:39
wuyanmin
Rank: 1
等 级:新手上路
帖 子:10
专家分:1
注 册:2010-5-29
得分:0 
看了一些资料,现在错误更加多了,5555555555……
2011-04-28 21:43



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-336903-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.051900 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved