本文轉自:http://www.cnblogs.com/showlie/articles/751737.html
SerialPort中串口資料的讀取與寫入有較大的不同。由於串口不知道資料何時到達,因此有兩種方法可以實現串口資料的讀取。一、線程即時讀串口;二、事件觸發方式實現。
由於線程即時讀串口的效率不是十分高效,因此比較好的方法是事件觸發的方式。在SerialPort類中有DataReceived事件,當串口的讀緩衝有資料到達時則觸發DataReceived事件,其中SerialPort.ReceivedBytesThreshold屬性決定了當串口讀緩衝中資料多少個時才觸發DataReceived事件,預設為1。
另外,SerialPort.DataReceived事件運行比較特殊,其運行在輔線程,不能與主線程中的顯示資料控制項直接進行資料轉送,必須用間接的方式實現。如下:
SerialPort spSend; //spSend,spReceive用虛擬串口串連,它們之間可以相互傳輸資料。spSend發送資料
SerialPort spReceive; //spReceive接受資料
TextBox txtSend; //發送區
TextBox txtReceive; //接受區
Button btnSend; //資料發送按鈕
delegate void UpdateTextEventHandler(string text); //委託,此為重點
UpdateTextEventHandler updateText;
public void InitClient() //表單控制項已經初始化
{
updateText = new UpdateTextEventHandler(UpdateTextBox); //執行個體化委派物件
spSend.Open(); //SerialPort對象在程式結束前必須關閉,在此說明
spReceive.DataReceived += new Ports.SerialDataReceivedEventHandler(spReceive_DataReceived);
spReceive.Open();
}
public void btnSend_Click(object sender,EventArgs e)
{
spSend.WriteLine(txtSend.Text);
}
public void spReceive_DataReceived(object sender,Ports.SerialDataReceivedEventArgs e)
{
//byte[] readBuffer = new byte[spReceive.ReadBufferSize];
//spReceive.Read(readBuffer, 0, readBuffer.Length);
//this.Invoke(updateText, new string[] { Encoding.Unicode.GetString(readBuffer) });
string readString = spReceive.ReadExisting();
this.Invoke(updateText,new string[] {readString});
}
private void UpdateTextBox(string text)
{
txtReceive.Text = text;
}
SerialPort中串口資料的讀取與寫入有較大的不同。由於串口不知道資料何時到達,因此有兩種方法可以實現串口資料的讀取。一、線程即時讀串口;二、事件觸發方式實現。
由於線程即時讀串口的效率不是十分高效,因此比較好的方法是事件觸發的方式。在SerialPort類中有DataReceived事件,當串口的讀緩衝有資料到達時則觸發DataReceived事件,其中SerialPort.ReceivedBytesThreshold屬性決定了當串口讀緩衝中資料多少個時才觸發DataReceived事件,預設為1。
另外,SerialPort.DataReceived事件運行比較特殊,其運行在輔線程,不能與主線程中的顯示資料控制項直接進行資料轉送,必須用間接的方式實現。如下:
SerialPort spSend; //spSend,spReceive用虛擬串口串連,它們之間可以相互傳輸資料。spSend發送資料
SerialPort spReceive; //spReceive接受資料
TextBox txtSend; //發送區
TextBox txtReceive; //接受區
Button btnSend; //資料發送按鈕
delegate void UpdateTextEventHandler(string text); //委託,此為重點
UpdateTextEventHandler updateText;
public void InitClient() //表單控制項已經初始化
{
updateText = new UpdateTextEventHandler(UpdateTextBox); //執行個體化委派物件
spSend.Open(); //SerialPort對象在程式結束前必須關閉,在此說明
spReceive.DataReceived += new Ports.SerialDataReceivedEventHandler(spReceive_DataReceived);
spReceive.Open();
}
public void btnSend_Click(object sender,EventArgs e)
{
spSend.WriteLine(txtSend.Text);
}
public void spReceive_DataReceived(object sender,Ports.SerialDataReceivedEventArgs e)
{
//byte[] readBuffer = new byte[spReceive.ReadBufferSize];
//spReceive.Read(readBuffer, 0, readBuffer.Length);
//this.Invoke(updateText, new string[] { Encoding.Unicode.GetString(readBuffer) });
string readString = spReceive.ReadExisting();
this.Invoke(updateText,new string[] {readString});
}
private void UpdateTextBox(string text)
{
txtReceive.Text = text;
}