Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

serial port - C# SerialPort.Write occasionally fails with "The requested resource is in use"

I have a piece of code that is reading and writing from a 115200 baud serial port. From what I can tell, the port is receiving bytes just fine but when I try to write to the port, I occasionally get a "The requested resource is in use" exception. This exception is raised by a SerialStream member inside the SerialPort. The serial port is using a USB Serial Adapter Driver (FTDI I believe...).

What could be causing this to occur? Could the reads be blocking the writes to the serial port?

    // 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, 0, 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, 0, 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);
    }

In the main program, we set the serial port's dataRecievedHandler to the ReadBuffer function above. At the same time, we have an async task running the PollLoop to ping the remote device. Occasionally, the write function will return this exception:

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 offset, 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.

I've looked around and haven't been able to find anyone with similar issues. It's usually an issue with opening the serial port.

Some ideas as to why this could be failing:

  1. The process data function is in the same thread that is reading from the socket. I don't think this should prevent a function from pushing data onto the write queue but maybe when it goes to flush out to the socket, resources are locked up?
  2. There is a Task.Delay() in the PollLoop function. Could this have any affect on the write?
  3. The baud rate is rather high (115200)... Is that enough to keep the serial port busy reading?

If something fails to write, is it valid to try writing it again or would that push multiple copies onto the SerialPort's write queue?

Thanks!

question from:https://stackoverflow.com/questions/65909898/c-sharp-serialport-write-occasionally-fails-with-the-requested-resource-is-in-u

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...