Calling SerialPort.ReadLine() directly on the WPF UI thread risks freezing the window whenever a hardware response is delayed.
Serializing Command–Response Calls with Timeouts
Hardware/SerialCommandChannel.cs
C# / .NET
public async Task<string> SendCommandAsync(string cmd, TimeSpan timeout, CancellationToken ct = default)
{
await _mutex.WaitAsync(ct);
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(timeout);
_port.DiscardInBuffer();
_port.WriteLine(cmd);
return await Task.Run(() => _port.ReadLine(), cts.Token);
}
finally
{
_mutex.Release();
}
}