problem accessing main thread's listbox

Oct 27 2008 2:45 AM
How am i going to display items in a listbox processed by 2 threads. The first thread is the main thread that displays the messages to the listbox typed from a textbox after a button click is performed. The second thread updates the same listbox by listening from incoming messages and will display those messages in the listbox using listbox.invoke method..Pls. help ..Thanks

my code:  X is a class library     

   public Form1()
        {
           
            InitializeComponent();
            x= new X.ClientSocket();
            IntPtr handle = this.Handle;
            x.IPadd = "127.0.0.1";
            x.Port = 8222;
            x.Connect();
           
            ThreadStart threadStarter = new ThreadStart(ReceiveMessages);
            myThread = new Thread(threadStarter);
            myThread.IsBackground = true;
            myThread.Start();
           
        }


        private void ReceiveMessages()
        {
                while (x.bytesCount>=0)
                {
                                   
                    this.listBox1.Invoke(new UpdateTextCallback(this.Update_listBox1), new object[] { x.getSenderMessage });
                }                                 //can't understand why is that when i use textbox here the code runs ok..
                                                    //or if i use Thread.Sleep , but will loop several times.
          
        }



        private void Update_listBox1(String text)
        {
           listBox1.Items.Add(text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                x.Send(textBox1.Text, textBox2.Text, richTextBox1.Text);
                listBox1.Items.Add(x.getMyMessage);
            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message+"---"+ex.StackTrace.ToString());
            }
        }