I am trying to add some safety around serial communication in .NET 6, but when nothing is connected to the port (on my testbed), I cannot properly dispose the port as any calls to SerialPort.Close() or SerialPort.Dispose() hangs.
I've managed to reduce it to the following MRE, which I am running on a Raspberry Pi 4 with Raspberry Pi OS. I'm building my application as framework dependent and portable.
using System.IO.Ports;
var sp = new SerialPort("/dev/ttyAMA0", 38400)
{
DataBits = 8,
Parity = Parity.None,
StopBits = StopBits.One,
WriteTimeout = TimeSpan.FromSeconds(3).Seconds,
ReadTimeout = TimeSpan.FromMilliseconds(30).Seconds
};
try
{
sp.Open();
sp.WriteLine("123");
}
catch (Exception) { }
finally
{
Console.WriteLine("Closing");
sp.Close(); //Hangs here
Console.WriteLine("Closed");
Console.ReadLine();
}
Is there anything I can do to avoid my application hanging?