Softivation

C# ground control station freezes: separate the UI from the data stream

If your C# ground control station freezes while telemetry keeps flowing, the problem isn't the link but switching to the UI on every packet. Here's the cause, working code, and the error messages.

Furkan IŞIKAY 6 min read

You wrote your own ground control station in C#. The connection is established, the numbers are flowing, and then the window locks up. You move the mouse and the title bar turns white. There's nothing wrong with the telemetry link. The link works; the drawing side can't keep up.

The trap here is that the link is much faster than you expect. You're interrupting the UI on every incoming packet.

How the bytes reach the UI

The incoming pile of bytes is first split into frames, then written somewhere. You make the decision right at this write: do you write the value directly to the control on screen, or to a field that sits in between?

See the two paths side by side with the same stream in the figure below. On top, the value is written directly to the control on screen; at the bottom, to a locked field in between.

Same stream, different number of switches to the UI

How many times the UI is switched to while the reading thread receives each frame: once per frame when switching on every packet, once every 100 ms with a fixed refresh
Where to look: the frame frequency in the reading strip is the same in both panels. The difference is the number of arrows going down to the UI strip.

In the top path, the thread doing the reading has to switch to the UI thread after every frame and wait until its turn comes. A single switch is cheap; thousands per second lock up the window.

The number of calls sets the cost

When you consume the same telemetry stream with the two designs, the stream, the duration, and the number of decoded frames stay almost the same. The only thing that changes is how many times the UI is switched to: in 15 seconds, the design that switches on every packet switches 20,482 times for 20,482 frames, while the design refreshing at 10 Hz switches 150 times for 20,454 frames.

A real UI both waits and draws on every switch. Once the drawing work is added, the message queue starts piling up and the window stops responding.

One detail muddies things here. If your ground control station doesn't send heartbeats to the autopilot and doesn't request streams, the autopilot sends you only a few packets per second. When you turn the streams on, this number multiplies. So on your first try the UI looks perfectly smooth, and on the day you turn the streams on it freezes.

Separate the reading side from the UI

The fix is to switch to the UI less often. The reading thread writes to a locked field and doesn't touch any control. A separate loop wakes up at a fixed rate, takes a snapshot of that field, and refreshes the screen in one go.

C#shared state and refresh loop
sealed class TelemetriDurumu
{
    readonly object _kilit = new();
    long _paket; int _sonMesajId; DateTime _sonGorulme;

    public void Uygula(int mesajId)
    {
        lock (_kilit) { _paket++; _sonMesajId = mesajId; _sonGorulme = DateTime.UtcNow; }
    }

    public (long paket, int mesajId, DateTime an) Oku()
    {
        lock (_kilit) { return (_paket, _sonMesajId, _sonGorulme); }
    }
}

// Refresh loop: stays constant no matter the packet rate.
var tazeleme = Task.Run(async () =>
{
    var sonCizim = DateTime.UtcNow;
    while (!dur.IsCancellationRequested)
    {
        await Task.Delay(50, CancellationToken.None);
        if (sonCizim.AddMilliseconds(100) > DateTime.UtcNow) continue;  // 10 Hz
        sonCizim = DateTime.UtcNow;

        var (paket, mesajId, an) = Durum.Oku();
        // In WinForms a single BeginInvoke replaces this line.
        ArayuzuCiz(paket, mesajId, an);
    }
});

With a refresh rate of 10 Hz, the number of switches to the UI stays constant whatever the packet rate. Ten refreshes per second is enough for a UI that looks smooth.

If you run this design in a sample program for 20 seconds, you get output like this:

Output
decoded frames : 29616
UI updates : 192
UI updates / frame : 0.65 %
son mesaj id      : 11030

The program decodes more than twenty-nine thousand frames and switches to the UI only 192 times. That's a ratio of six and a half per thousand.

Example: in a swarm flight, telemetry from three vehicles arrives at the same ground station. In the design that switches to the UI on every packet, the number of switches grows with the number of vehicles, and a window that copes with one vehicle freezes with three. With a locked field and a 10 Hz refresh, even if the packet count triples, the UI still draws ten times per second. The number of vehicles doesn't change how smooth the window is.

Error Messages and Their Meanings

Most of the time you'll experience this failure without getting any error. But these are the strings you may run into the moment you access a control from the reading thread.

Cross-thread operation not valid: Control '...' accessed from a thread other than the thread it was created on.

You tried to access a control's window from the reading thread. Whether this check is on doesn't depend on the build configuration but on whether a debugger is attached when the process starts. So in a build you run without a debugger, the same wrong code passes silently and behaves oddly now and then.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

A switch to the UI was attempted before the form was even on screen. This usually shows up when the connection is started in the constructor or in a reading loop started before the form loads.

The I/O operation has been aborted because of either a thread exit or an application request.

The port was closed while reading was still going on. Reverse the closing order: stop the loop first, wait for it to finish, then close the port.

Probable I/O race condition detected while copying memory.

The same buffer is being used by two threads at once. Keep the read buffer owned by a single thread.

More in the course

This article explains what the problem looks like and how to separate the design. The counter that stops the queue from piling up, the closing order, board-specific differences, and their counterparts in the source code of a real ground control station are covered step by step in the C# Course from Beginner to Advanced.

Softivation YKİ library: start with a MAVLink connection, Turkish documentation, and a ready-made test interface when you write your own ground control station in C#.

Was this article helpful?

Free resourcePixhawk and ArduPilot error message glossaryThe 3 messages in this article and similar ones are in the glossary: what they mean, why they appear, what to check first.

Learn this topic from start to finish

Season plan: all six courses for 9 months, ₺790 a month. ₺390 a month for high school and university students, ₺351 the first month with your member code. You can stop in any month you like. Start the Season plan · I'm a student