views:

226

answers:

4

Hi All,

I keep getting the following error when debugging.

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

Here's the code that it points to:

    public  void OnDataReceived(IAsyncResult asyn)
    {
        try
        {
            SocketPacket socketData = (SocketPacket)asyn.AsyncState ;

            int iRx  = 0 ;
            // Complete the BeginReceive() asynchronous call by EndReceive() method
            // which will return the number of characters written to the stream 
            // by the client
            iRx = socketData.m_currentSocket.EndReceive (asyn);
            char[] chars = new char[iRx +  1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(socketData.dataBuffer, 
                                     0, iRx, chars, 0);
            System.String szData = new System.String(chars);
            richTextBoxReceivedMsg.AppendText(szData);

            // Continue the waiting for data on the Socket
            WaitForData( socketData.m_currentSocket );
        }
        catch (ObjectDisposedException )
        {
            System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
        }
        catch(SocketException se)
        {
            MessageBox.Show (se.Message );
        }
    }

Can somebody please help me fix this? I appreciate any help at all

Thank you

+3  A: 

You need to replace this:

richTextBoxReceivedMsg.AppendText(szData);

with something like

Invoke(new Action(() => richTextBoxReceivedMsg.AppendText(szData)));

The reason is that Windows Forms is not really designed to work across different threads. Invoke method will run the delegate you pass to it in the UI thread. If you want to manipulate UI elements via other threads, you'll have to run the actual manipulation on the UI thread. InvokeRequired property will tell you when you need to use Invoke rather than calling the method directly.

Mehrdad Afshari
Thank you, Mehrdad. :) - ... It displays a message saying "Cannot convvert anonymous method to type 'System.Delegate' because it is not a delegate."
lucifer
@j-t-s: I always get this wrong and forget the argument to invoke is `System.Delegate`. This should fix it.
Mehrdad Afshari
@Mehrdad - Thank you :)
lucifer
A: 

Check out Jon Skeet's article on multi-threading, particularly the page on multi-threading winforms. It should fix you right up.

magnifico
Thank you very much, @magnifico. Very interesting read!
lucifer
A: 

This link may be able to help you.

Otávio Décio
Thank you Otavio, looking at it now :)
lucifer
A: 

check by writing the given statement in your form1() constructor RichTextBox.CheckForIllegalCrossThreadCalls = false;

Thank u....

Kiran