Skip to content

System.IO.Ports.SerialPort: Under Linux, closing the port while writing cause a deadlock. #100690

@sylvainouel

Description

@sylvainouel

Description

If you write from one thread and close the port from another, it is possible for the Write to lockup and never return.
It doesn't repro on Windows.

Reproduction Steps

The following reproduces the issue very quickly.

using System.IO.Ports;

var s = new SerialPort();
s.PortName = args[0];
Console.WriteLine("Using port {0}",s.PortName);

var t = new Thread(() =>
{
    while (true)
    {
        try {
            Console.WriteLine("Say hello");
            s.Write("Hello World");
        } catch (Exception e)
        {}
    }
});
t.Start();

while (true)
{
    s.Open();
    Thread.Sleep(1);
    s.Close();
}

In SerialStreamUnix.cs:
Write eventually calls WriteAsync which queues a SerialStreamWriteRequest then calls EnsureIOLoopRunning.
EnsureIOLoopRunning acquires a lock (_ioLoopLock), however, Dispose does not, stops the ioLoop and writes to _ioLoop.
The IOLoop is stopped, and the request never completes.

Expected behavior

Write should always return or throw.

Actual behavior

it locks up after only a few iteration

Regression?

No response

Known Workarounds

  • add lock around Close and Write
  • Set a WriteTimeout

Configuration

tested with:
.NET 7.0.17
Linux ARM64

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions