Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi,
I am testing a Tcp client C# windows form application I am able to send data to Tcp server Software(Hercules 3.2.8) But when i sent data from Tcp server to windows form then i am getting the following error:

System.InvalidOperationException: Cross-Thread operation not valid: Control 'MessageList' accessed from a thread other than the threa it was control on. at System.Windows.Forms.ListBox.ObjectCollection.Add(Object item)
at WindowsFormsAppication1.Form1.MessageCallBack(IAsyncResult ar) in From1.cs:line 55

Line 55 is at Messagelist.items.Add(response);

C#
    public partial class Form1 : Form
    {
        Socket sck;
        EndPoint remoteEp;
        byte[] buffer;
        IPAddress ip = IPAddress.Parse("192.168.42.143");
        int port = 8061;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            RemoteIptxt.Text = ip.ToString();
            Remoteporttxt.Text = port.ToString();
            //setup socket
            sck = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        }

        private void Connectbtn_Click(object sender, EventArgs e)
        {
            //binding socket
            remoteEp = new IPEndPoint(IPAddress.Parse(RemoteIptxt.Text), Convert.ToInt32(Remoteporttxt.Text));
            sck.Connect(remoteEp);

            buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEp, new AsyncCallback(MessageCallBack), buffer);
        }

        private void MessageCallBack(IAsyncResult ar)
        {
            try
            {
                byte[] receiveData = new byte[1500];
                receiveData = (byte[])ar.AsyncState;
                //Converting byte[] to string
                ASCIIEncoding ascencoding = new ASCIIEncoding();
                string response = ascencoding.GetString(receiveData);

                //Adding message to listbox
                MessageList.Items.Add(response);

                buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEp, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            //convert string message to byte[]
            ASCIIEncoding ascencoding = new ASCIIEncoding();
            byte[] sendmess = new byte[1500];
            sendmess = ascencoding.GetBytes(textMessage.Text);
            sck.Send(sendmess);
            MessageList.Items.Add("You Said:" + textMessage.Text);
            textMessage.Text = "";
        }

     
    }
}


What I have tried:

I am beginner in socket programming So i don't know how to create thread safe program
Please help...!!!
Posted
Updated 12-Jan-18 5:53am

1 solution

You cannot access any UI control from any thread other than the one it was created on: the UI thread (which is the only one running at the start of your app). If you try, you get a Cross-threading exception as you have seen.

If you look at the documentation:
The BeginReceiveFrom method starts asynchronously reading connectionless datagrams from a remote host. Calling the BeginReceiveFrom method gives you the ability to receive data within a separate execution thread.
It does make it pretty clear that your callback method is executed on a different thread - i.e. a non-UI thread.

To access any UI Control from you callback method, you must Invoke it:Control.Invoke Method (Delegate) (System.Windows.Forms)[^]
 
Share this answer
 
Comments
Member 13479861 12-Jan-18 12:06pm    
Can you please simplify the solution code for my question the Microsoft documentation is a complete bouncer for me.could you please write the Thread invoke method for my example.
OriginalGriff 12-Jan-18 12:19pm    
Would you like me to come round and type it in for you as well?
Member 13479861 12-Jan-18 12:24pm    
Its ohk thank you I have been working on this tcp client program from past few days i got stuck with the errors upon errors.Thats the reason i asked you for a particular code for my problem anyways thank you
OriginalGriff 12-Jan-18 12:49pm    
Read the link - it's not complicated, and if you are going to work with threading you need to be able to do this stuff; you can't ask me every time you need another line of code! :laugh:
Richard Deeming 12-Jan-18 12:58pm    
Replace:
MessageList.Items.Add(response);

with:
Invoke((Func<string, int>)MessageList.Items.Add, response);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900