The UI thread, Invoke and BeginInvoke

A WinForms application has one thread that owns every window. It created them, it pumps their messages, and it is the only thread allowed to touch them. Work that takes time must run somewhere else, and the result must come back: Invoke, BeginInvoke and InvokeRequired are the three members that do it, and they are a small part of the base library once the rule is understood.

One thread owns a control

A handle belongs to the thread that created it. Windows queues a message for a window on the thread that owns the window, and the message loop of that thread dispatches it. A control is a window with a handle, so a control belongs to the thread that created its handle, which is the thread that ran Application.Run.

Touching a control from another thread is not always an exception. It is undefined: sometimes it works, sometimes the text is lost, sometimes the window handles are recreated under it and the call fails much later. In debug builds WinForms makes the common cases loud with InvalidOperationException: Cross-thread operation not valid, guarded by Control.CheckForIllegalCrossThreadCalls, which is true by default when a debugger is attached. A release build is silent about the same bug, which is the reason the rule matters even when the debugger is quiet.

The rule in one sentence: the thread that created the control may read and write it; every other thread must ask that thread to do it. The asking is what Invoke does.

Invoke, InvokeRequired and BeginInvoke

A delegate passed to Invoke runs on the UI thread, inside the message loop, with the UI thread's identity. That is the whole mechanism: it is the message loop that serialises the calls, not a lock. Which also means the delegate must be short. A long computation inside an Invoke freezes the window exactly as if it had run there directly.

A worker and a label

The form starts a background thread, which sleeps and reports a step. Each report checks InvokeRequired and marshals the assignment. The last report uses BeginInvoke, because the worker has nothing left to do. Built and not run:

using System; using System.Drawing; using System.Threading; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly Label _status = new() { Location = new Point(16, 20), AutoSize = true }; private readonly Button _start = new() { Text = "&Start", Location = new Point(16, 56), Size = new Size(100, 27) }; private readonly Button _stop = new() { Text = "Sto&p", Location = new Point(124, 56), Size = new Size(100, 27), Enabled = false }; private CancellationTokenSource? _cancel; public Form1() { Text = "Work in the background"; ClientSize = new Size(360, 120); _start.Click += OnStart; _stop.Click += OnStop; Controls.Add(_status); Controls.Add(_start); Controls.Add(_stop); } private void OnStart(object? sender, EventArgs e) { _start.Enabled = false; _stop.Enabled = true; _cancel = new CancellationTokenSource(); var token = _cancel.Token; var worker = new Thread(() => { for (var i = 1; i <= 5; i++) { if (token.IsCancellationRequested) { return; } Thread.Sleep(200); var text = $"step {i}"; if (_status.InvokeRequired) { _status.Invoke(() => _status.Text = text); } else { _status.Text = text; } } _status.BeginInvoke(() => Finished("done")); }) { IsBackground = true, }; worker.Start(); } private void OnStop(object? sender, EventArgs e) => _cancel?.Cancel(); private void Finished(string text) { _status.Text = text; _start.Enabled = true; _stop.Enabled = false; } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. IsBackground means the thread does not keep the process alive if the form closes, which is what a worker on a screen wants. The token is captured in a local before the thread starts, so the worker reads the token of this run and not whatever the field holds when a second run begins.

The InvokeRequired check is what lets one method be correct from any thread: on the UI thread it takes the direct path, and from a worker it marshals. Without the check the method could only be called from one of the two, and the rule would have to be remembered by every caller instead of being written where the control is.

The deadlock

The classic way to hang a WinForms application is to wait on the UI thread for a call that waits on the UI thread. This line is the whole bug:

private void OnLoad(object? sender, EventArgs e) { var worker = new Thread(() => _status.Invoke(() => _status.Text = "done")); worker.Start(); worker.Join(); }

The handler runs on the UI thread. Join blocks that thread until the worker exits. The worker is inside Invoke, waiting for the UI thread to run its delegate, and the UI thread is waiting for the worker. Neither ever moves, and the window stops repainting. The same shape appears with Task.Wait, Task.Result and a lock held across an Invoke; the fix is never to block the UI thread on work that needs it, which is what async and await are for (lesson 062).

The fragment above is not built by this page: it has no Main and is not a program. The deadlock is described from the documented behaviour of Join and Invoke, and the course does not run it, because a run would hang until the check's timeout.

A queue that runs

The mechanism behind Invoke can be written in forty lines: a thread with a blocking queue, a Post that adds to it, and an Invoke that adds and waits. The program below runs that dispatcher and prints the order, which is the order a form would see:

using System; using System.Collections.Concurrent; using System.Threading; Console.WriteLine("a queue owned by one thread"); var ui = new UiThread(); ui.Start(); ui.Invoke(() => Console.WriteLine("hello from the UI thread")); Console.WriteLine("main: Invoke returned"); ui.Post(() => Console.WriteLine("posted work")); ui.Invoke(() => Console.WriteLine("barrier: everything posted before me has run")); Console.WriteLine("main: Post returned before this line"); var worker = new Thread(() => { ui.Invoke(() => Console.WriteLine($"the worker's Invoke ran in {Thread.CurrentThread.Name}")); Console.WriteLine("worker: Invoke returned"); }) { Name = "worker", }; worker.Start(); worker.Join(); ui.Stop(); Console.WriteLine("main: queue closed"); internal sealed class UiThread { private readonly BlockingCollection<Action> _queue = new(); private readonly Thread _thread; public UiThread() { _thread = new Thread(Run) { Name = "ui" }; } public void Start() => _thread.Start(); public void Post(Action action) => _queue.Add(action); public void Invoke(Action action) { if (Thread.CurrentThread == _thread) { action(); return; } using var done = new ManualResetEventSlim(); _queue.Add(() => { action(); done.Set(); }); done.Wait(); } public void Stop() { _queue.CompleteAdding(); _thread.Join(); } private void Run() { foreach (var action in _queue.GetConsumingEnumerable()) { Console.WriteLine("ui: running one item"); action(); } } }

dotnet run

a queue owned by one thread
ui: running one item
hello from the UI thread
main: Invoke returned
ui: running one item
posted work
ui: running one item
barrier: everything posted before me has run
main: Post returned before this line
ui: running one item
the worker's Invoke ran in ui
worker: Invoke returned
main: queue closed

The output is the real run. Invoke printed before the line after it, because it waited. Post printed after the line that follows it, because the second Invoke acted as a barrier and ran only after the posted item. The worker's delegate ran in the thread named ui, not in worker, which is the whole promise of marshalling. The same three lines on Windows are the ones a form sees, with Control.Invoke and the message loop in place of this queue.

One difference from the real control is worth naming. The queue has no notion of a handle or of a message, so it cannot be closed by the destruction of a window; Stop is explicit. The rest of the rule is the same on both: a delegate handed to Invoke from the owning thread runs in place, and from another thread it crosses the boundary first, which is what decides how it gets there.

Exercises

  1. Change the barrier Invoke to a Post and run the program. Which output lines can now come in either order?
  2. Add a Send method to UiThread that does what Invoke does and explain why the real control has no separate name for it.
  3. Change the form to use BeginInvoke for every step and explain what the label shows if two steps finish out of order.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which thread may touch a control?

    Answer

    The thread that created its handle

    The handle belongs to the creating thread and its message loop.

  2. What does InvokeRequired tell a worker?

    Answer

    Whether it is on another thread and must marshal

    It is the check before Invoke.

  3. What does Invoke do that BeginInvoke does not?

    Answer

    It waits until the delegate has run

    BeginInvoke posts and returns at once.

  4. What did the run show about the worker's Invoke?

    Answer

    It ran in the thread named ui

    The delegate runs on the owner thread, which is the promise.

  5. Why did posted work print after the main line that follows the Post call?

    Answer

    Post returns at once; the following Invoke was the barrier

    The run prints the barrier before that main line.

  6. Why does the deadlock example hang?

    Answer

    The UI thread waits on Join while the worker waits on the UI thread

    Each thread waits for the other.

  7. Which call on the UI thread has the same deadlock shape?

    Answer

    Task.Result or Task.Wait

    They block the thread that the awaited work needs.

  8. Why must a delegate passed to Invoke be short?

    Answer

    It runs on the UI thread and freezes the window if it is long

    The message loop is blocked while it runs.

  9. What is ISynchronizeInvoke?

    Answer

    The interface behind Invoke, BeginInvoke and InvokeRequired

    A Control implements it, so code can depend on the interface.

  10. Why is the cross-thread exception not always seen in a release build?

    Answer

    The check is a debug aid; a release build is silent about the same bug

    The rule applies in both builds; only the diagnostic differs.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev