C# SerialPort.Write 偶尔会失败并显示“请求的资源正在使用中”

问题描述

我有一段从 115200 波特串行端口读取和写入的代码。据我所知,端口接收字节很好,但是当我尝试写入端口时,我偶尔会收到“请求的资源正在使用”异常。此异常由 SerialPort 内的 SerialStream 成员引发。串行端口正在使用 USB 串行适配器驱动程序(我相信是 FTDI...)。

什么可能导致这种情况发生?读取是否会阻止对串​​行端口的写入?

    // Constructor
    public MySerialPort()
    {
        Port = this;
        PortBufSize = 4096;
        Port_rxbuf = new byte[PortBufSize];
        Port.PortName = "COM1"; //default Windows port
        Port.Baudrate = 115200;
        Port.Parity = Parity.None;
        Port.DataBits = 8;
        Port.StopBits = StopBits.One;
        Port.Handshake = Handshake.None;
        Port.RtsEnable = true;
        Port.DtrEnable = true;
        Port.ReceivedBytesThreshold = 1024;
        Port.ReadTimeout = 500;
        Port.WriteTimeout = 500;
        Port.Encoding = Encoding.Unicode;
    }


    // Called from the dataRecievedHandler
    public int ReadBuffer()
    {
        int bytesreadtotal = 0;
        try
        {
            do
            {
                int lenread = Port.Read(m_readbuf,m_readbufsize);
                ProcessBytes(lenread);
                bytesreadtotal += lenread;
                LastDataReceived = DateTime.Now;
            }
            while (Port.BytesToRead != 0);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message,"Error!");
        }

        return bytesreadtotal;
    }

    // Write function
    public void WriteBuffer(byte[] buf)
    {
        try
        {
            Port.Write(buf,buf.Length);
        }
        catch (Exception ex)
        { 
            // This throws the exception
            Console.WriteLine(ex);
        }

    }

    // This function sends bytes out every 6 seconds
    public async Task PollLoop()
    {
        int count = 6;
        do
        {
            WriteBuffer(SomeByteBuffer);
            while (count-- > 0 && m_run)
                await Task.Delay(1000);
            count = 6;

        }
        while (m_run);
    }

在主程序中,我们将串口的dataRecievedHandler设置为上面的ReadBuffer函数。同时,我们有一个异步任务运行 PollLoop 来 ping 远程设备。偶尔,write 函数会返回这个异常:

System.IO.IOException: The requested resource is in use.

   at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode,String str)
   at System.IO.Ports.SerialStream.EndWrite(IAsyncResult asyncResult)
   at System.IO.Ports.SerialStream.Write(Byte[] array,Int32 offset,Int32 count,Int32 timeout)
   at System.IO.Ports.SerialPort.Write(Byte[] buffer,Int32 count)
   at Comms.MySerialPort.WriteBuffer(Byte[] txbuf) in 
   C:/project/Class1.cs:line 446
Error writing to serial port :: The requested resource is in use.

我环顾四周,没有找到任何有类似问题的人。通常是打开串口的问题。

关于为什么会失败的一些想法:

  1. 进程数据函数在从套接字读取的同一个线程中。我不认为这应该阻止函数将数据推送到写入队列,但也许当它刷新到套接字时,资源被锁定了?
  2. PollLoop 函数中有一个 Task.Delay()。这会对写入产生任何影响吗?
  3. 波特率相当高(115200)...这足以让串口忙于读取吗?

如果写入失败,尝试再次写入是否有效,或者是否会将多个副本推送到 SerialPort 的写入队列?

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)