dotnet/runtime

SerialStream discards 'numBytes', resulting in data loss

Open

#97,549 opened on Jan 26, 2024

View on GitHub
 (3 comments) (1 reaction) (0 assignees)C# (5,445 forks)batch import
area-System.IO.Portshelp wanted

Repository metrics

Stars
 (17,886 stars)
PR merge metrics
 (Avg merge 12d 11h) (661 merged PRs in 30d)

Description

This issue has been moved from a ticket on Developer Community.


[severity:It's more difficult to complete my work] The SerialStream implementation discards numBytes returned by the async write: https://github.com/microsoft/referencesource/blob/master/System/sys/system/IO/ports/SerialStream.cs#L1186-L1209

Consequently, the caller of Write() has no clue on how much data got written during the operation, that would allow the caller to retransmit the yet missing data. The SerialStream implementation should return the number of bytes written as return value of Write(), allowing e.g. SerialPort.Write() returning the value as well.

The attached app demonstrates the issue. Requirements:

  • Visual Studio 2022 or above
  • Two interconnected serial COM ports (loopback)

DataLoss.zip

The app demonstrates how a write operation times out, i.e. only part of the data of 2048 is actually written to Tx, but there neither is a TimeoutException nor can the caller retrieve the number of effectively written bytes, as numBytes is discarded by the SerialStream implementation.

grafik.png

Note that increasing WriteTimeout would eventually fix the issue in this very app, it could even use the default of InfiniteTimeout. However, if hardware or software flow control is required, simply increasing WriteTimeout is no good idea, the port would hang in Write(). Worst case: The counterpart disables flow control and then crashes or breaks, resulting in the port hanging forever. Therefore, WriteTimeout must be set to a small enough value.

Returning numBytes would be a pretty simple solution to this issue. And since no caller today excepts Write() to return a value, the change would only be breaking in terms of the function's signature, not its behavior.


Original Comments

Feedback Bot on 06/12/2023, 04:51 AM:

(private comment, text removed)

Eirik George Tsarpalis [MSFT] on 26/01/2024, 01:00 PM:

(private comment, text removed)

Contributor guide