PQ
← Back to all articles
Tech & Software • • 7 min read

Reliable Serial Port Communication in .NET WPF: Avoiding Lost Commands and UI Freezes

Practical pattern for communicating with motor controllers and sensors over COM ports using SemaphoreSlim and timeouts.

CONTENTS (1)

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();
    }
}