简体   繁体   English

几个小时后,C# 无法读取串口?

[英]C# can't read serial port after few hours?

i have a project which read serial port data from device, and My operating system is windows 10. i Have read this :我有一个从设备读取串口数据的项目,我的操作系统是 Windows 10。我读过这个:

  1. C# Serial Port Check if Device is Connected C#串口检查设备是否连接

2. SerialPort.Close() freezes application if the USB COM Port in use has been removed 2. 如果正在使用的 USB COM 端口已被移除,SerialPort.Close() 会冻结应用程序

but my code may only work 6 hours if there is no input from device.但是如果没有来自设备的输入,我的代码可能只能工作 6 小时。 The solution for now is close form after that open form again.现在的解决方案是再次打开表单后关闭表单。

 SerialPort myPort = new SerialPort();
   private void Scanning_Load(object sender, EventArgs e)
    {
        myPort.BaudRate = 9600;
        myPort.PortName = "COM4";
        if (SerialPort.GetPortNames().ToList().Contains(comPortname))
        {
            if (!myPort.IsOpen)
            {
                myPort.Open();
            }
             myPort.DataReceived += getReceivedata;
        }
     }
    private  void getReceivedata(object sender,
                             SerialDataReceivedEventArgs e)
    {
        SerialPort spL = (SerialPort)sender;
        string data_rx = spL.ReadLine();
        this.Invoke((MethodInvoker)delegate
        {
         Console.Write(data_rx);
        });
    }

This may be a result of power management (or power options) settings.这可能是电源管理(或电源选项)设置的结果。 You didn't state which OS you're using, or if your device is attached via USB.您没有说明您使用的是哪个操作系统,或者您的设备是否通过 USB 连接。

Win 10:赢10:

  • In search box next to Start icon, type: device manager在“开始”图标旁边的搜索框中,键入:设备管理器
  • Right-click your desired device右键单击您想要的设备
  • Select "Properties"选择“属性”
  • If "Allow the computer to turn off this device to save power" option exits, uncheck it.如果“允许计算机关闭此设备以节省电源”选项退出,请取消选中它。 Click OK.单击确定。

Other settings that you may need to review are "Power Options" which can be found in the Control Panel or in search box next to Start icon, type: power options (then click "Additonal power settings").您可能需要查看的其他设置是“电源选项”,它可以在控制面板或开始图标旁边的搜索框中找到,键入:电源选项(然后单击“其他电源设置”)。 Since you stated that it works for 6 hours.既然你说它可以工作6个小时。 You might check which settings are set at 6 hours (360 minutes).您可以检查哪些设置设置为 6 小时(360 分钟)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM