2011-11-27 4 views
2

나는 내가 메인 창 (MainForm)에서하여 RichTextBox (TXT) 내가 SerialTranseiver (MainForm 백만)라는 다른 양식 통과 한다른 폼의 스레드에서 폼의 RichTextBox에 텍스트를 붙여 넣는 방법?

public void postTxt(String txt) 
{ 
    //do some database update 
    this.Txt.AppendText(txt); 
} 

공개 방법을 C# 어디에요에서 윈도우 폼 응용 프로그램이 MainForm을 생성자의 매개 변수로 사용합니다.

SerialTranseiver(MainForm mn) 
{ 
    //-----other codes 
    this.tmpMain=mn; 
} 

이 두 번째 클래스는하여 SerialPort (스포츠)와 데이터를 대기하고있다 자사의 SerialDataReceivedEventHandler에있는 데이터는 mn.postTxt (Sport.ReadLine(). toString())

void Sport_DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    mn.postTxt(Sport.ReadLine().toString()); 
    //---database updating codes and other stuff 
} 

를 호출 할 때마다 이로 인해

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

예외가 발생합니다.이 문제를 어떻게 해결할 수 있습니까?

답변

1

한 가지 방법은 비동기 적으로 대리인을 호출하는 것입니다.이 대리인은 사용자가 호출하는 형식으로 공개됩니다. 예를 들어 :

:

mainForm.BeginInvoke(mainForm.logDelegate,destination,fileName,bytesSent, true); 

난 그냥이 게시물을 읽고 문제를 해결하기 위해 먼저 this

0

이후

this을 읽는 게 좋을 것

귀하의 c ase, 시도해보십시오.

void Sport_DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    if (this.InvokeRequired) 
    { 
     this.Invoke(new MethodInvoker(() => Sport_DataReceived(sender, e))); 
     return; 
    } 

    mn.postTxt(Sport.ReadLine().toString()); 
    //---database updating codes and other stuff 
} 
관련 문제