c# - SerialPort.Open() 抛出 IOException - 系统资源不足,无法完成请求的服务

标签 c# .net serial-port ioexception

我有一个我编写的 .NET 4 Windows 服务,它定期(通常一天一次)通过串行端口与外部设备通信。总而言之,该服务运行良好,但对于一位客户,时不时调用 SerialPort.Open() 会引发以下异常:

System.IO.IOException: Insufficient system resources exist to complete the requested service.
at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
at System.IO.Ports.SerialPort.Open()

Based on the exception, would would think that the server is running low on resources, but that doesn't seem to be the case. The CPU is more or less idle and there's plenty of memory and disk.

There are lots of mentions online of SerialPort.Open() throwing other IOExceptions and I have implemented Zach Saw's SerialPortFixer, but it appears it fixes a different issue.

Here's an example of what I'm doing (greatly simplified). A couple of instances of this class (using different serial port names) are in memory at all times and then the Run() method is called approximately once a day for each instance.

public class Collector
{
    private SerialPort _port;
    private string _portName;

    public void Run()
    {
        try
        {
            // Run Zach Saw's IOException workaround
            SerialPortFixer.Execute(_portName);

            using (_port = new SerialPort(_portName, 9600, Parity.None, 8, StopBits.One))
            {
                _port.DataReceived += PortDataReceived;
                _port.ErrorReceived += PortErrorReceived;
                _port.Handshake = Handshake.None;
                _port.DtrEnable = true;
                _port.RtsEnable = true;

                _port.Open();
                // Do the stuff
                _port.Close();
            }
        }
        catch (Exception e)
        {
            // Handle exception
        }
    }

    private void PortDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        // Do other stuff
    }

    private void PortErrorReceived(object sender, SerialErrorReceivedEventArgs e)
    {
        // Log error
    }
}

如有任何帮助,我们将不胜感激。

最佳答案

这个问题的答案是客户端使用的串口服务器是wi-fi版本(Moxa NPort W2150 Plus),结果发现串口服务器出现wi-fi连接问题时出现异常。

关于c# - SerialPort.Open() 抛出 IOException - 系统资源不足,无法完成请求的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14961303/

相关文章:

c# - 喜欢在 Active Directory 中搜索

.net - WCF命名管道安全性和多个用户 session ?

c# - ObjectContext 实例已被处置,不能再用于需要连接错误级联下拉列表的操作

c# - 隐藏代码不能像 XAML 那样工作

c# - 嵌套或不嵌套的 if block ?

python - 使用 Python 串行读取 MATLAB 单曲

java - 如何将字符串转换为十六进制和将十六进制转换为字符串?

C UART 始终不工作

c# - Swagger 未显示在 Azure 上

.Net 核心连接到 mongo db 不工作