C# 串口读取(事件驱动)

来源:互联网 发布:ecel表格数据有效性 编辑:程序博客网 时间:2024/06/05 17:48

网上有一个JustinIO类,是针对于串口操作写的类.工作需要我得用串口把读卡机的信息拿取出来.开始用这个类写是无非用一个while循环调用JustinIO的Read方法.但这样写发现系统架构上不是很好.于是我在原来的JustinIO类中加入了ReadEvent事件.也就是把JustinIO类封装成一个由事件驱动的类(当串口有数据入时会触发ReadEvent事件).具体如下:

public delegate void ReadEventHandler( object sender, byte [] Buffer );
 class CommPort {

//声明事件
  public event ReadEventHandler ReadEvent;

  public bool Done = true;

...

...          //由于JustinIO类网络可以下载,它原有的代码我会省略

public void Open()
  {

                  .....

                  Thread th = new Thread( new ThreadStart( Execut ));
                   th.Start();

}

private void Execut()
  {
                  while ( Done )
                 {
                        byte [] Buffer = this.Read( 128 );
                        if ( Buffer.Length > 0 )
                         {
                                   OnReadEvent( Buffer );
                         }
                 }
  }

private void OnReadEvent( byte [] Buffer )
  {
                 if ( ReadEvent != null )
                {
                          ReadEvent( this , Buffer );
                 }
  }

public void Close()
  {
             Done = false;
             if (hComm!=INVALID_HANDLE_VALUE)
              {
                           CloseHandle(hComm);
               }
  }

}

就是样已经为JustinIO类添加了一个事件.

在调用方只要绑定这人事件就可以了.

private CommPort commPort;

private void Init()
  {
            commPort = new CommPort();
            commPort.PortNum = "COM1";
            commPort.BaudRate = 9600;
            commPort.ByteSize = 8;
            commPort.Parity = 0;
            commPort.StopBits = 0;//1;
            commPort.ReadTimeout = 2000;
            try
            {
                     if ( commPort.Opened )
                                     commPort.Close();

                    commPort.Open();

                     if ( commPort.Opened )
                     { 
                                      commPort.ReadEvent += new ReadEventHandler( OnRead );
                      }
             }
             catch( Exception ex )
              {
                                    MessageBox.Show(ex.Message);
              }
  }
  public void OnRead( object sender , byte [] Buffer )
  {
                MessageBox.Show( System.Text.Encoding.ASCII.GetString(Buffer ) );
  }

这样做对于调用层来说再清楚不过了.我不需要知道它怎么读,只需要知道它读到信息时会触发OnRead函数.

原创粉丝点击