我想做个socket来测试测试,结果服务器端老是出错:说是“跨執行緒作業無效: 存取控制項 'listBox1' 時所使用的執行緒與建立控制項的執行緒不同。”
出错的地方是“label1.Text = iep.ToString();”和“listBox1.Items.Add(msg);”。
我该如何是好,请大仙们帮帮我~~!
以下是代码
private void BeginListen()
        {
            IPAddress ServerIP = GetServerIP();
            IPEndPoint iep = new IPEndPoint(ServerIP, 8000);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            byte[] byteMessage = new byte[100];
            label1.Text = iep.ToString();
            socket.Bind(iep);
            while (true)
            {
                try
                {
                    socket.Listen(5);
                    Socket newSocket = socket.Accept();
                    newSocket.Receive(byteMessage);                    string sTime = DateTime.Now.ToShortTimeString();
                    string msg = sTime + ":Message from:";
                    msg += newSocket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
                    listBox1.Items.Add(msg);
                }
                catch (SocketException ex)
                {
                    label1.Text += ex.ToString();
                }
                
            }
        }

解决方案 »

  1.   

    // The following code assumes a 'ListBox' and a 'Button' control are added to a form, 
    // containing a delegate which encapsulates a method that adds items to the listbox.   public class MyThreadClass
       {
          MyFormControl myFormControl1;
          public MyThreadClass(MyFormControl myForm)
          {
             myFormControl1 = myForm;
          }      public void Run()
          {
             // Execute the specified delegate on the thread that owns
             // 'myFormControl1' control's underlying window handle.
             myFormControl1.Invoke(myFormControl1.myDelegate);
          }
       }
      

  2.   

    BeginListen方法是不是另外开了一个线程,如果是这样的话,看看下面的代码是否对你有用
    if (this.InvokeRequired)
                {
                    this.Invoke(new TestDelegate(TestEventHandler), new object[] { obj});
                    return;
                }
    这个代码只是参照,你直接用肯定不行,你可以查一下InvokeRequired以及Invoke的用法
      

  3.   


    与此楼的方法的方法差不多,楼主去查下Invoke,InvokeRequired相关资料。
      

  4.   

    private void BeginListen()
            {
                IPAddress ServerIP = GetServerIP();
                IPEndPoint iep = new IPEndPoint(ServerIP, 8000);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                byte[] byteMessage = new byte[100];
                label1.Text = iep.ToString();//需要在invoke中
                socket.Bind(iep);
                while (true)
                {
                    try
                    {
                        socket.Listen(5);
                        Socket newSocket = socket.Accept();
                        newSocket.Receive(byteMessage);                    string sTime = DateTime.Now.ToShortTimeString();
                        string msg = sTime + ":Message from:";
                        msg += newSocket.RemoteEndPoint.ToString() + Encoding.Default.GetString(byteMessage);
                        listBox1.Items.Add(msg); //需要在invoke中
                    }
                    catch (SocketException ex)
                    {
                        label1.Text += ex.ToString(); //需要在invoke中
                    }
                    
                }
            }
      

  5.   

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Threading;   public class MyFormControl : Form
       {
          public delegate void AddListItem(String myString);
          public AddListItem myDelegate;
          private Button myButton;
          private Thread myThread;
          private ListBox myListBox;
          public MyFormControl()
          {
             myButton = new Button();
             myListBox = new ListBox();
             myButton.Location = new Point(72, 160);
             myButton.Size = new Size(152, 32);
             myButton.TabIndex = 1;
             myButton.Text = "Add items in list box";
             myButton.Click += new EventHandler(Button_Click);
             myListBox.Location = new Point(48, 32);
             myListBox.Name = "myListBox";
             myListBox.Size = new Size(200, 95);
             myListBox.TabIndex = 2;
             ClientSize = new Size(292, 273);
             Controls.AddRange(new Control[] {myListBox,myButton});
             Text = " 'Control_Invoke' example ";
             myDelegate = new AddListItem(AddListItemMethod);
          }
          static void Main()
          {
             MyFormControl myForm = new MyFormControl();
             myForm.ShowDialog();
          }
          public void AddListItemMethod(String myString)
          {
                myListBox.Items.Add(myString);
          }
          private void Button_Click(object sender, EventArgs e)
          {
             myThread = new Thread(new ThreadStart(ThreadFunction));
             myThread.Start();
          }
          private void ThreadFunction()
          {
             MyThreadClass myThreadClassObject  = new MyThreadClass(this);
             myThreadClassObject.Run();
          }
       }
       public class MyThreadClass
       {
          MyFormControl myFormControl1;
          public MyThreadClass(MyFormControl myForm)
          {
             myFormControl1 = myForm;
          }
          String myString;      public void Run()
          {
             for (int i = 1; i <= 5; i++)
             {
                myString = "Step number " + i.ToString() + " executed";
                Thread.Sleep(400);
                // Execute the specified delegate on the thread that owns
                // 'myFormControl1' control's underlying window handle with
                // the specified list of arguments.
                myFormControl1.Invoke(myFormControl1.myDelegate,
                                       new Object[] {myString});
             }
          }
       }
      

  6.   

     AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(null);
     asyncOperation.Post
     {
       delegate
       {BeginListen();},null
     };