-3

This is the error :

**

Exception thrown: 'System.InvalidOperationException' in System.Windows.Forms.dll Additional information: Cross-thread operation not valid: Control 'displayText' accessed from a thread other than the thread it was created on.

**

I was created multi threaded client and server application using on C#. I was researched about this error but I could not find any relevant answer. I know this is comes when two or more threads started on the program...But my server side has one thread...I don't know why this is comes..........

Here is my Server side:

        private void Handler()
        {
            try {


                byte[] b = new byte[100];
                int k = s.Read(b, 0, b.Length);

                //int k = s.Receive(b);



                string szReceived = Encoding.ASCII.GetString(b,0,k);
                //If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks,


                while (ServerRunning)
                {
                    string ConcatString = "";
                    for (int i = 0; i < k; i++)
                    {

                        char n = Convert.ToChar(b[i]);
                        string chars = Convert.ToString(n);
                        ConcatString = ConcatString + chars;

                    }

                    if (b[0] == '$')
                    {
                        displayText.AppendText("\nPrivate Message");
                        //MessageBox.Show("\nPrivate Message" + Environment.NewLine);
                    }
                    else
                    {
                        displayText.AppendText("\n" + ConcatString);
                        //MessageBox.Show(ConcatString + Environment.NewLine);
                    }

                    //Encoding is the process of transforming a set of Unicode characters into a sequence of bytes and using new instance
                    ASCIIEncoding asen = new ASCIIEncoding();

                    //s.Send(asen.GetBytes("The string was recieved by the server." + Environment.NewLine));

                    displayText.AppendText("\n" + ConcatString);
                    /* clean up */
                    //*
                   // k = s.Receive(b);
                    s.Close();
                    client.Close();
                    //MessageBox.Show("Recieved..." + Environment.NewLine);


                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error ...." + ex);
            }
        }

I am new to Socket Programming, but I was researched each and every code segment and experimented the code in several times.. Still can't figure out what exactly I missed in this program...

So please help me to solve this...I will be appreciated very much... Thanks..

  • 1
    the error you're getting is because you tried to update the UI from another thread which you cannot do, Im not convinced it didnt receive the message, the title and body of this post dont match – BugFinder Apr 07 '17 at 09:52
  • Your server is receiving the message, but you are trying to access the `displayText` control from another thread - you cannot do this. – Matt Hogan-Jones Apr 07 '17 at 09:55
  • Look at the question that @rene mentions and how about trying to understand the actual error you've got - notice how it mentions nothing about sockets... – Matt Hogan-Jones Apr 07 '17 at 09:56
  • Learn to debug first - then step through the code. – Matt Hogan-Jones Apr 07 '17 at 09:56
  • again, the error you are describing has **nothing to do with the socket code**, and everything to do with how you are touching the UI; forget about sockets for now, that doesn't seem to be the problem – Marc Gravell Apr 07 '17 at 09:57
  • Yeh, Sockets, it is not the problem, the case is only appears when I send a message to the server – Jamunath Hunga Apr 07 '17 at 09:58

1 Answers1

1
Invoke((MethodInvoker) delegate { displayText.AppendText("\n" + ConcatString); });

should fix it; that dispatches the "append to the UI" code to the UI thread and waits for it to complete.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • @PiyasenaSenani `Invoke` is the `Form.Invoke` method, [here](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.invoke(v=vs.110).aspx); `MethodInvoker` is just a well-known delegate type that is special-cased by `Invoke` for performance (rather than using `Delegate.DynamicInvoke`). Basically, it just creates a runnable code fragment and says "hey, UI: run this for me while I wait" – Marc Gravell Apr 07 '17 at 10:01
  • 2
    @PiyasenaSenani again, this has **nothing to do with sockets**, and everything to do with the fact that you're touching the UI from a non-UI thread – Marc Gravell Apr 07 '17 at 10:01
  • @PiyasenaSenani of course it is threading - that's exactly what the exception told you; see your code here: `Thread tcpHandlerThread = new Thread(Handler); tcpHandlerThread.Start();` - that runs the `Handler` method ***on a different thread***. That thread is not allowed to directly touch the UI. – Marc Gravell Apr 07 '17 at 10:04