C#2.0中,SerialPort運行方式

 
C#2.0中,SerialPort運行方式[轉載]
 
[點評:這幾天一直用這個控件,可是老是有問題,也許這篇文章是解決問題最終的辦法了.] SerialPort中串口數據的讀取與寫入有較大的不同。由於串口不知道數據何時到達,因此有兩種方法可以實現串口數據的讀取。
    一、線程實時讀串口;
    二、事件觸發方式實現。
     由於線程實時讀串口的效率不是十分高效,因此比較好的方法是事件觸發的方式。在SerialPort類中有DataReceived事件,當串口的讀緩存有數據到達時則觸發DataReceived事件,其中SerialPort.ReceivedBytesThreshold屬性決定了當串口讀緩存中數據多少個時才觸發DataReceived事件,默認爲1
    另外,SerialPort.DataReceived事件運行比較特殊,其運行在輔線程,不能與主線程中的顯示數據控件直接進行數據傳輸,必須用間接的方式實現。如下:
SerialPort spSend; //spSend,spReceive用虛擬串口連接,它們之間可以相互傳輸數據。spSend發送數據
SerialPort spReceive; //spReceive接受數據
TextBox txtSend; //發送區
TextBox txtReceive; //接受區
Button btnSend; //數據發送按鈕
delegatevoid HandleInterfaceUpdateDelegate(string text); //委託,此爲重點
HandleInterfaceUpdateDelegate interfaceUpdateHandle; publicvoid InitClient() //窗體控件已在初始化
...{ interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(UpdateTextBox); //實例化委託對象
spSend.Open(); //SerialPort對象在程序結束前必須關閉,在此說明
spReceive.DataReceived += Ports.SerialDataReceivedEventHandler(spReceive_DataReceived); spReceive.ReceivedBytesThreshold = 1; spReceive.Open(); }
publicvoid btnSend_Click(object sender,EventArgs e) ...{ spSend.WriteLine(txtSend.Text); }
publicvoid spReceive_DataReceived(object sender,Ports.SerialDataReceivedEventArgs e) ...{ byte[] readBuffer = newbyte[spReceive.ReadBufferSize]; spReceive.Read(readBuffer, 0, readBuffer.Length); this.Invoke(interfaceUpdateHandle, newstring[] ...{ Encoding.Unicode.GetString(readBuffer) }); }
privatevoid UpdateTextBox(string text) ...{ txtReceive.Text = text; }
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章