C# 串口事件委托
2013-09-06 17:22
176 查看
由于线程实时读串口的效率不是十分高效,因此比较好的方法是事件触发的方式。在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;
}
相关文章推荐
- c#之再战委托事件多线程2_委托和事件结合降低模块低耦合
- 编写高质量代码改善C#程序的157个建议——建议138:事件和委托变量使用动词或形容词短语命名
- [C#] C#中的委托和事件
- C#控制台基础 事件可以在本类中当做委托来调用,但是在其他类不可以直接调用
- C#中的委托和事件(续)
- C#的委托及事件 猫叫人醒老鼠跑
- 菜鸟入门 认识C#中的委托和事件
- 事件与委托详解 Delegate (c#)
- C#笔记 委托与事件
- 大师级写的C# 中的委托和事件 简明扼要
- C# 委托和事件
- 第七章:委托和事件--委托(c#高级编程 第6版)
- C#编程之委托与事件(一)
- C# 中的委托和事件
- C# 中的委托和事件
- C#基础笔记——委托(Delegate)和事件(Event)
- 大白话系列之C#委托与事件讲解
- C#利用lambda实现委托事件的挂接
- C# 委托与事件
- C# 中的委托和事件