日期:2014-05-18 浏览次数:20961 次
首先是一个SerialportEx单例类,里面模拟了发送,接收,触发事件等等功能 namespace WindowsFormsApplication1 { /// <summary> /// 数据到达的委托 /// </summary> /// <param name="text"></param> public delegate void DataArrivalHandler(String text); /// <summary> /// 一个模拟Serialport的单例类 /// </summary> public class SerialportEx { /// <summary> /// 数据到达的事件 /// </summary> public event DataArrivalHandler OnDataArrival; /// <summary> /// 单例,密封 /// </summary> private SerialportEx() { } /// <summary> /// 单例对象 /// </summary> public static readonly SerialportEx Instance = new SerialportEx(); /// <summary> /// 模拟数据到达 /// </summary> /// <param name="text"></param> private void DataArrival(String text) { if (OnDataArrival != null) { // 触发事件,通知上层 OnDataArrival(text); } } /// <summary> /// 模拟接收数据 /// </summary> public void StartReceive() { ThreadPool.QueueUserWorkItem(new WaitCallback(Send), null); } /// <summary> /// 模拟模拟,全都是模拟 /// </summary> /// <param name="obj"></param> private void Send(Object obj) { while (true) { DataArrival(System.DateTime.Now.ToString()); System.Threading.Thread.Sleep(1000); } } } }
------解决方案--------------------
使用事件和委托