Update the UI from Another Thread in C# (WinForms)

Windows Forms controls may only be touched from the thread that created them, the UI thread. Set a label’s Text from a worker thread and, with the debugger attached, you get:

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

Without the debugger the check is off by default, which is worse: the code appears to work and then fails randomly, freezes or corrupts the control.

There are three ways to get the update back onto the UI thread. In new code, async/await and IProgress<T> cover almost every case and you never call Invoke yourself. Control.Invoke and BeginInvoke are still the tools for callbacks from code you don’t control.

The examples are WinForms, so Windows-only: the project targets net8.0-windows with <UseWindowsForms>true</UseWindowsForms>, as dotnet new winforms creates it.

async and await: run the work, then update

If the background work produces a result and the UI only needs it at the end, await Task.Run is all you need:

private async void CountButton_Click(object? sender, EventArgs e)
{
    countButton.Enabled = false;
    statusLabel.Text = "Counting...";

    try
    {
        int primes = await Task.Run(() => CountPrimes(5_000_000));
        statusLabel.Text = $"Found {primes:N0} primes.";
    }
    finally
    {
        countButton.Enabled = true;
    }
}

private static int CountPrimes(int limit)
{
    int count = 0;

    for (int n = 2; n <= limit; n++)
    {
        bool isPrime = true;

        for (int d = 2; d * d <= n; d++)
        {
            if (n % d == 0)
            {
                isPrime = false;
                break;
            }
        }

        if (isPrime) count++;
    }

    return count;
}

Task.Run executes CountPrimes on a thread pool thread. The await captures the UI thread’s synchronization context, so every line after it, including the statusLabel update and the finally block, runs on the UI thread again. No Invoke anywhere. Notice also that CountPrimes is static and takes its input as a parameter: background code that cannot see the form cannot accidentally touch a control.

The async and await examples explain the mechanics, and why async void is fine for event handlers but nowhere else.

Report progress while the work runs

For progress bars and status messages during the work, pass an IProgress<T> to the background method. Progress<T> captures the synchronization context of the thread that creates it and runs its callback there:

private CancellationTokenSource? cts;

private async void StartButton_Click(object? sender, EventArgs e)
{
    startButton.Enabled = false;
    cancelButton.Enabled = true;
    cts = new CancellationTokenSource();
    CancellationToken token = cts.Token;

    var progress = new Progress<int>(percent =>
    {
        progressBar.Value = percent;
        statusLabel.Text = $"{percent}%";
    });

    try
    {
        await Task.Run(() => DoWork(progress, token));
        statusLabel.Text = "Done.";
    }
    catch (OperationCanceledException)
    {
        statusLabel.Text = "Cancelled.";
    }
    finally
    {
        cts.Dispose();
        cts = null;
        startButton.Enabled = true;
        cancelButton.Enabled = false;
    }
}

private void CancelButton_Click(object? sender, EventArgs e) => cts?.Cancel();

private static void DoWork(IProgress<int> progress, CancellationToken token)
{
    for (int i = 1; i <= 100; i++)
    {
        token.ThrowIfCancellationRequested();
        Thread.Sleep(50); // stands in for real work
        progress.Report(i);
    }
}

DoWork knows nothing about forms or threads; it reports numbers. That makes it easy to test and reuse from a console app or a service. Create the Progress<T> on the UI thread, as here; created on a worker thread, it has no UI context to post to.

Report posts the callback asynchronously and does not wait for it. If you report on every item of a million-item loop, you flood the message queue and the UI becomes sluggish. Report every few hundred items, or only when the percentage changes.

Control.Invoke and BeginInvoke

Some code calls you back on a thread you didn’t choose: SerialPort.DataReceived, socket callbacks, System.Threading.Timer, or events from a third-party library. There you marshal the update yourself:

private void AppendLog(string message)
{
    if (logTextBox.InvokeRequired)
    {
        logTextBox.BeginInvoke(() => AppendLog(message));
        return;
    }

    logTextBox.AppendText(message + Environment.NewLine);
}

AppendLog can now be called from any thread. InvokeRequired is true when the caller is not on the control’s thread.

The difference between the two methods:

  • Invoke runs the delegate on the UI thread and blocks the calling thread until it has finished. Use it when the worker needs a value back from the UI. It deadlocks if the UI thread is itself waiting for that worker, for example in task.Wait() or a lock the worker holds.
  • BeginInvoke posts the delegate and returns immediately. It is the safer default for fire-and-forget updates like logging.

Old examples wrap the lambda in new Action(...) or (MethodInvoker)(...). That cast was needed because Invoke takes a Delegate, and before C# 10 a lambda had no type of its own to convert from. With C# 10 or later, the plain lambda compiles.

Two classes can do the marshalling for you: set SynchronizingObject = this on a FileSystemWatcher or a System.Timers.Timer, and their events are raised on the form’s UI thread. And if you only need a timer that updates the UI, System.Windows.Forms.Timer already ticks on the UI thread.

Traps when the form closes

Background work that outlives the form will try to update disposed controls, and Invoke or BeginInvoke on a control whose window handle is gone throws an InvalidOperationException or ObjectDisposedException. Cancel running work in FormClosing (the CancellationTokenSource above makes that a one-liner) rather than catching those exceptions after the fact.

Also note that InvokeRequired returns false if the control’s handle has not been created yet, even when you are on the wrong thread. Don’t start background work that touches controls from the form’s constructor; use the Load or Shown event.

WPF works the same way with different names: Dispatcher.Invoke and Dispatcher.BeginInvoke instead of the Control methods, while async/await and Progress<T> are identical.

Related examples

Leave a Comment