Cross-thread operation not valid: Control 'txtIn' accessed from a thread other than the thread it was created on.

I am trying to make a TCP IP Client control and when I receive a message, or basically when the receiver text box is updated, it crashes my client due to cross threading.

How would I fix this?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Collections;
using System.Threading;
using System.Net;

namespace Client
{
    public partial class Form1 : Form
    {
    	private System.Windows.Forms.TextBox ip;
        private System.Windows.Forms.TextBox txtName;
        private System.Windows.Forms.TextBox txtOut;
        private System.Windows.Forms.Label status;
        private System.Windows.Forms.Label bitchinLabel;
        private System.Windows.Forms.Button sendButton;
        private System.Windows.Forms.Button disconnectButton;
        private System.Windows.Forms.Button exitButton;
        private System.Windows.Forms.Label headerLabel;
        private System.Windows.Forms.Label line;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label statusLabel;
        private System.Windows.Forms.Button btnConnect;
    	
    	Socket client;
		EndPoint remoteEP;
		byte[] data;
		int recv;
		
		private System.Windows.Forms.TextBox txtIn;
		
		private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        
        public Form1()
        {
            InitializeComponent();
            
        }


private void btnConnect_Click(object sender, EventArgs e)
        {
            client = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
			remoteEP = new IPEndPoint(IPAddress.Parse(ip.Text.Trim()), 1337);
			client.SendTo(Encoding.ASCII.GetBytes("join"), remoteEP);
			data = new byte[1024];
			Thread thread1 = new Thread(new ThreadStart(Receive));
			thread1.Start();
        }
        private void disconnectButton_CLICK(object sender, EventArgs e){
			client.SendTo(Encoding.ASCII.GetBytes("quit"), remoteEP);
        }
        private void send_Click(object sender, System.EventArgs e)
		{
			
			Thread thread = new Thread (new ThreadStart(Send));
			thread.Start();
			
		}
    	private void exitButton_CLICK(object sender, EventArgs e)
        {
    		this.Close();
    	}
    	
    	
    	public void Send() 
		{
			client.SendTo(Encoding.ASCII.GetBytes(txtName.Text.Trim() + " :" + txtOut.Text.Trim()), remoteEP);
		}
    	public void Receive() {
			while(true) 
			{
				recv = client.ReceiveFrom(data, ref remoteEP);
				txtIn.Text += Encoding.ASCII.GetString(data, 0, recv) + "\r\n" ;
			}
    	}

Create an updater delegate and method to invoke the call on the proper thread:

private void frmInvoke_Load(object sender, EventArgs e)
    {
      port = new SerialPort();
      port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    }

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
      SetMessageText(port.ReadExisting());
    }

    public delegate void SetText(string s);
    public void SetMessageText(string s)
    {
      if (textBox1.InvokeRequired)
      {
        textBox1.Invoke(new SetText(SetMessageText), s);
      }
      else
      {
        textBox1.Text = s;
      }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.