3

If the SerialPort.Write() is a blocking operation( or is it not?), what would be the need for the BytesToWrite() method. It would always evaluate to zero, cause the last Write operation either succeeded in writing all data or failed, in either case the bytes to be written would be come zero.

Perhaps, there is more to it then what I have described.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176

3 Answers3

4

SerialPort.Write is a blocking operation, yes. However, there are two buffers to be considered: The serial device, and the SerialPort buffers.

If the SerialPort object is configured to buffer, the write only blocks if there isn't enough room in that buffer. It will block for as long as it takes the buffer to empty enough to fit the new data. Otherwise it fills the buffer and returns.

If the SerialPort object does not buffer, the Write operation blocks only for as long as it takes to transfer the data to the serial device. That device has its own buffer(*), so the block may take far less time than the time it will take to send the data.

SerialPort.BytesToWrite includes both data in the device's buffer and data in the SerialPort object's buffer.

(*) Older UARTs did not have buffers and newer ones do but can be configured to not buffer.

Tergiver
  • 14,171
  • 3
  • 41
  • 68
2

Serial ports are very slow I/O devices that date from the stone age of computing. At a common baudrate of 9600 bits per second, it can only transmit a bit less than thousand bytes per second. Compare to a hard disk, a burst speed of 60,000,000 bytes per second is possible. Or more comparable, a network card can transmit 125,000,000 bytes per second.

So the serial port driver keeps a buffer that stores the bytes you write and slowly empties it while they are written by the UART chip. That buffer allows the Write() call to quickly return. Given that it is so slow, you might want to be aware of how full that buffer is so that you can avoid blocking on the Write() call. WriteBufferSize - BytesToWrite tells you how much space is available in that buffer.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

The SerialPort property BytesToWrite Gets the number of bytes of data in the send buffer.

On the other hand the SerialPort method Write(string text) Writes the specified string to the serial port.

You do know how a serial port works right? A serial sends a certain amount of bytes every second depending on the baud used.

Security Hound
  • 2,577
  • 3
  • 25
  • 42