2010-02-12 21 views
6

Sigo recibiendo el siguiente error al depurar.Operación entre hilos no válida

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

Aquí está el código que apunte a:

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); 
    } 
} 

Puede alguien por favor me ayude a solucionar esto?

+0

No vuelvas solucionar este problema mediante el establecimiento de CheckForIllegalCrossThreadCalls a falso. Solo pretende que no hay problema en vez de arreglarlo ... – user2141066

Respuesta

21

es necesario sustituir este:

richTextBoxReceivedMsg.AppendText(szData); 

con algo como

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

La razón es que las formas de Windows no es realmente diseñado para trabajar a través de diferentes temas. El método Invoke ejecutará el delegado que le pase en el subproceso de interfaz de usuario. Si desea manipular elementos de la interfaz de usuario a través de otros hilos, tendrá que ejecutar la manipulación real en el hilo de la interfaz de usuario. La propiedad InvokeRequired le dirá cuándo debe usar Invoke en lugar de llamar al método directamente.

+1

Gracias, Mehrdad. :) - ... Muestra un mensaje que dice "No se puede convertir el método anónimo para escribir 'System.Delegate' porque no es un delegado". –

+0

@ j-t-s: Siempre me sale mal y olvido que el argumento para invocar es 'System.Delegate'. Esto debería arreglarlo. –

2

Consulte el artículo de Jon Skeet sobre multi-threading, particularmente la página en multi-threading winforms. Debería arreglarte.

+1

Muchas gracias, @magnifico. Lectura muy interesante! –

0

This link puede ser capaz de ayudarte.

+1

Gracias Otavio, mirándolo ahora :) –

-1

check escribiendo la declaración dada en su form1() constructor RichTextBox.CheckForIllegalCrossThreadCalls = false;

gracias u ....

+0

Esto está funcionando. –

Cuestiones relacionadas