Skip to content

C# windows chat application

akshay rasalakar

Asked Jun 13, 2015, 7:00 PM EDT2 answers
Share
LinkedInX
C#
private void MessageCallBack(IAsyncResult aResult)
        {
            int size = sck.EndReceiveFrom(aResult, ref epRemote);
            if (size > 0)
            {
                byte[] recevivedData = new byte[1464];

                recevivedData = (byte[])aResult.AsyncState;

                ASCIIEncoding eEncoding = new ASCIIEncoding();
                string recevieMessage = eEncoding.GetString(recevivedData);
listBox1.Items.Add("Friend:" + recevieMessage); //In this Line Im getting error Cross-thread operaation not valid: Control 'listBox1' accessed from a                                                                                     thread other than the thread it was created on
                                                                                   i can send msg to my friend but while receiving the message im getting the error as i mentioned above                                                                                     so pls help me..
Code
            }
            byte[] buffer = new byte[1500];

            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
        }

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Manoj Bhoir
    0
    Hi,
     
    You must interact with a control on the UI thread.
    You can use Control.InvokeRequired[^] to determine if you're on the UI tread or not. If you're not on the UI thread you have to use Control.Invoke[^] or Control.BeginInvoke[^]
     
    So, Instead of this line :
     
    listBox1.Items.Add("Friend:" + recevieMessage);
     
    Write :
     
    Code
    listBox1.Invoke(new MethodInvoker(delegate()
                    {
    listBox1.Items.Add("Friend:" + recevieMessage);
       }));
    0
  • 1 short reply
    • 0
      thanks U sir its working
      0