我的异步套接字是按书上的,但vs2005上运行出错异常
//单击按钮的处理函数
        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "connecting...";
            Socket network = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("202.194.147.198"), 9050);
            network.BeginConnect(iep, new AsyncCallback(Connected), network);        }
//asyncCallback方法,label1是个标签控件
        void Connected(IAsyncResult iar)
        {
            client = (Socket)iar.AsyncState;
            string str = "error connect";
            event1(this, str);            try
            {
                client.EndConnect(iar);
                label1.Text = "connected to:" + client.RemoteEndPoint.ToString();
                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(ReceiveData), client);            }
            catch (SocketException)
            {
                label1.Text = "error connected";//在这里出现异常
            }
}
这是为什么啊?有办法改吗?

解决方案 »

  1.   

    Windows控件,只能在创建它的线程里访问它,
    在不同的线程访问,要通过当前线程的Invoke方法来调用。
      

  2.   

    加上这个委托
            private delegate void setLabeText(Label lbl, string strInfo);
            private void SetLabelText(Label lbl, string str)
            {
                lbl.Text = str;
            }
    再将catch块里的语句替换成下面的
    label1.Invoke(new setLabeText(SetLabelText),new object []{label1,"errror connected!"});
      

  3.   

    这样写: 
           public FrmMain()
            {
                InitializeComponent();
                Control.CheckForIllegalCrossThreadCalls = false;
            }