• serialport DataReceived事件


    serialport DataReceived事件, 默认是收到一个byte就触发事件.

                lock (thisLock)
                {
                    int len = sp.BytesToRead;
                    if (len > 0)
                    {
                        Byte[] data = new Byte[len];
                        try
                        {
                            sp.Read(data, 0, len);
                        }
                        catch (System.Exception)
                        {
    
                        }
                        SerialPortEventArgs args = new SerialPortEventArgs();
                        args.receivedBytes = data;
                        Debug.WriteLine("**** port1_DataReceived=" + Encoding.Default.GetString(data));
                        if (comReceiveDataEvent != null)
                        {
                            comReceiveDataEvent.Invoke(this, args);
                        }
                    }
    
                }

    举个例子,实际上返回的数据是*IDN?, 但每次触发的次数都不一样

    **** port1_DataReceived=*
    **** port1_DataReceived=IDN?
    
    **** port1_DataReceived=*
    **** port1_DataReceived=I
    **** port1_DataReceived=DN?
    
    **** port1_DataReceived=*
    **** port1_DataReceived=I
    **** port1_DataReceived=D
    **** port1_DataReceived=N?
    
    **** port1_DataReceived=*
    **** port1_DataReceived=I
    **** port1_DataReceived=D
    **** port1_DataReceived=N
    **** port1_DataReceived=?
    
    **** port1_DataReceived=*
    **** port1_DataReceived=IDN
    **** port1_DataReceived=?
    
    **** port1_DataReceived=*
    **** port1_DataReceived=I
    **** port1_DataReceived=DN?

     DataReceived 事件的处理,本质上是用线程来处理接收数据.

    SerialPort类,请勿定义为局部变量, 因为局部变量在函数结束后就释放了.而线程还没结束,端口还没释放. 就会产生下面2种异常

    System.ObjectDisposedException was unhandled
    Message: An unhandled exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll
    Additional 
    
    information: 已关闭 Safe handle

    或者

    System.UnauthorizedAccessException was unhandled
      HResult=-2147024891
      Message=对端口“COM5”的访问被拒绝。
  • 相关阅读:
    http协议及http协议和tcp协议的区别
    Fastcgi协议定义解释与说明
    web请求响应
    Linux网络编程:一个简单的正向代理服务器的实现
    Nginx-请求处理与响应
    Nginx事件管理机制-epoll
    负载均衡
    Nginx-进程模型
    [转载]NGINX原理分析 之 SLAB分配机制
    Nginx惊群处理
  • 原文地址:https://www.cnblogs.com/zitjubiz/p/12268451.html
Copyright © 2020-2023  润新知