Jethro
Jethro

Reputation: 3359

SerialPort is Open but throws NullReferenceException on BytesToRead

I have A SerialPort created, and can check it is not null, and that SerialPort.IsOpen() returns true. But when I check the BytesToRead Property I get a NullReferenceException.

NullReferenceException: Object reference not set to an instance of an object
  System.IO.Ports.WinSerialStream.get_BytesToRead ()
  System.IO.Ports.SerialPort.get_BytesToRead ()
  (wrapper remoting-invoke-with-check) 
  System.IO.Ports.SerialPort:get_BytesToRead ()
  ...

I can step through with the debugger and see that immedietly before the BytesToRead call, the Serial Port is Instantiated and Open, but the debugger can't reach certain properties, including BytesToRead.

"System.IO.Ports.SerialPort"
    base: "System.IO.Ports.SerialPort"
    BaseStream: {System.IO.Ports.WinSerialStream}
    BaudRate: 9600
    BreakState: false
    BytesToRead: System.NullReferenceException: Object reference not set to an instance of an object
    BytesToWrite: System.NullReferenceException: Object reference not set to an instance of an object
    CDHolding: false
    CtsHolding: true
    DataBits: 8
    DiscardNull: System.NotImplementedException: The requested feature is not implemented.
    DsrHolding: false
    DtrEnable: false
    Encoding: {System.Text.ASCIIEncoding}
    Handshake: None
    IsOpen: true
    NewLine: "\r\n"
    Parity: None
    ParityReplace: System.NotImplementedException: The requested feature is not implemented.
    PortName: "COM3"
    ReadBufferSize: 4096
    ReadTimeout: 50
    ReceivedBytesThreshold: System.NotImplementedException: The requested feature is not implemented.
    RtsEnable: false
    StopBits: One
    WriteBufferSize: 2048
    WriteTimeout: -1

What could be going wrong?

Upvotes: 1

Views: 1624

Answers (1)

Jethro
Jethro

Reputation: 3359

It seems this has been a bug for Unity since 2016. They have "Postponed" working on it.

A Workaround is to use Experimental .NET 4.6 version, if you can migrate to that in your project without other problems.

https://issuetracker.unity3d.com/issues/serialport-bytestoread-returns-null-reference

Upvotes: 2

Related Questions