2017-05-12 40 views
2

這裏下面自動讀取串行端口的非常簡單的代碼: -串口在C#

public partial class MainForm : Form 
    { 
     public MainForm() 
     { 
     // 
     // The InitializeComponent() call is required for Windows Forms designer support. 
     // 
     InitializeComponent(); 

     // 
     // TODO: Add constructor code after the InitializeComponent() call. 
     // 


     serialPort1.PortName="COM11"; 
     serialPort1.Open(); 

    } 
    void SerialPort1DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
     rtBox.Text="Data Received\n"; 
    } 
    void BtnReadClick(object sender, EventArgs e) 
    { 
     rtBox.Text += "Read click" + "\n"; 
    } 

System.InvalidOperationException:跨執行緒作業無效:存取控制項 'rtBox' 時所使用的執行緒與建立控制項的執行緒不同。

谷歌翻譯中文字符 「不完整的線程作業:用於訪問控件'rtBox'的線程與建立控件的線程不同。 「

只是我只想在Rich測試框中顯示消息「數據接收」。但是,無論何時接收到數據,都有以下例外情況:

你知道爲什麼嗎?謝謝

+0

使用控件調用在UI線程中更新... –

回答

3

WinForm控件,如您的富文本框只能從主UI線程訪問。您的串行端口對象正在調用另一個事件處理程序。

你可以改變你的處理程序做這樣的事情 -

void SerialPort1DataReceived(object sender, SerialDataReceivedEventArgs e) 
{ 
    Invoke(new Action(() => 
    { 
     rtBox.Text="Data Received\n"; 
    }));   
} 

這將使用Control.Invoke然後將運行在UI線程內碼。

+2

謝謝。羅伯託..現在完美的工作。 –