threads + delegate em c#.net

boas,
eu ando a tentar meter-me no mundo das threads em c#.net (para depois implementar alg coisa com socks) e deparei-me com um problema. tentei seguir varias alternativas inclusive o uso d delegates (na minha opiniao um bocado difíceis) e n consigo obter um resultado positivo. Então o problema e este, tenho uma tabela(em ambiente gráfico claro) e quero continuamente meter la um simples "ola" sem ke o ambiente gráfico crash. So começa a meter "ola" kd pressiono o botão, só que ele da-me o seguinte erro:

"An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

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

ja tentei por o codigo de varias posicoes e nao caiu nd, ja ando a mto tempo a tentar. alguem que me possa ajudar??
o codigo em questao e este:

Código:
private void begin_simulacao(object sender, EventArgs e)
        {
            Thread oThread = new Thread(socks_t);
            oThread.Start();

            simulacao.Enabled = false;
        }




 delegate void tabela(string s, out int iExecThread);




 public void faz_tabela(string s, out int iExecThread)
        { tabela fazer = new tabela(faz_tabela);
          iExecThread = AppDomain.GetCurrentThreadId();
         
     if (dataGridView1.InvokeRequired == true)
             dataGridView1.Rows.Add(s);
         else
         {
            IAsyncResult ar = fazer.BeginInvoke("ola", out iExecThread, null, null);
            ar.AsyncWaitHandle.WaitOne();
            fazer.EndInvoke(out iExecThread, ar);
         }
        }

     
       
  public void socks_t()
        {
            
    int iExecThread;
    tabela fazer = new tabela(faz_tabela);
    

                while(true){

                    IAsyncResult ar = fazer.BeginInvoke("ola", out iExecThread, null,null);
                    ar.AsyncWaitHandle.WaitOne();

                fazer.EndInvoke(out iExecThread, ar);
                }

         
                
        }
    }
}
 
para escreveres nos tues control (cross thread calls), tens que fazer o seguinte:

Código:
private delegate void escreveDataGridHandler(string msg);
private void escreveDataGrid(string msg){			
   if (this.InvokeRequired){
      BeginInvoke(new escreveDataGridHandler(escreveDataGrid),new Object[] { msg});
      return;
   } else {	
								
       // Coloca aqui as tuas alterações aos control's GUI oriented... datagrids, textbox, labels, etc.   }
}


depois, dentro de uma thread qq , basta chamares.
Código:
private delegate void escreveDataGridHandler(string msg);
escreveDataGrid(" MENSAGEM");
}

/ing
 
Back
Topo