SynchronizationContext and IProgress

Invoke is the WinForms answer to a general problem: a piece of work runs on one thread and its result belongs on another. The base library abstracts the second thread as a SynchronizationContext, a small class with a Post and a Send. A WinForms control is one implementation, Progress<T> uses the abstraction, and a console program can supply its own. That is what makes the pattern testable here.

What a synchronization context is

A SynchronizationContext is the answer to one question: where should this delegate run? The base class has a default that runs it on the thread pool. A framework with a UI thread installs its own, and from then on any call that asks the current context to post runs on that thread. Two methods carry it:

The context is stored in SynchronizationContext.Current, which is a per-thread value: each thread has its own, and a queue is what makes them different. async and await capture the current context before an await and resume on it, which is the mechanism lesson 062 relies on.

The WinForms context and the console

WinForms installs a WindowsFormsSynchronizationContext on the UI thread when the first control is created with a handle. Its Post calls Control.BeginInvoke on a hidden control and its Send calls Control.Invoke. That is the whole relationship between the two lessons: Invoke is the control-level API, the context is the framework-level abstraction over it.

A console program has no such context: SynchronizationContext.Current is null, and a continuation after await resumes on the thread pool. That is why the program below sets one by hand: not to imitate WinForms, but to make the queue explicit and to print the order it produces.

Progress in a form

Progress<T> is the class a worker should take instead of a control: it captures the context it was created on, and its Report posts to that context. The form creates it on the UI thread, so every report arrives there. Built and not run:

using System; using System.Drawing; using System.Threading; using System.Threading.Tasks; 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 ProgressBar _bar = new() { Location = new Point(16, 20), Size = new Size(300, 20), Maximum = 100 }; private readonly Label _status = new() { Location = new Point(16, 48), AutoSize = true }; private readonly Label _context = new() { Location = new Point(16, 72), AutoSize = true }; private readonly Button _load = new() { Text = "&Load", Location = new Point(16, 100), Size = new Size(100, 27) }; public Form1() { Text = "Progress"; ClientSize = new Size(340, 140); Load += (sender, e) => _context.Text = SynchronizationContext.Current?.GetType().Name ?? "null"; _load.Click += OnLoad; Controls.Add(_bar); Controls.Add(_status); Controls.Add(_context); Controls.Add(_load); } private async void OnLoad(object? sender, EventArgs e) { _load.Enabled = false; var progress = new Progress<int>(value => { _bar.Value = value; _status.Text = $"{value}%"; }); await Task.Run(() => Report(progress)); _status.Text = "done"; _load.Enabled = true; } private static void Report(IProgress<int> progress) { for (var i = 0; i <= 100; i += 10) { Thread.Sleep(50); progress.Report(i); } } }

dotnet build app.csproj

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

The listing is built and not run. The Load handler prints the name of the context into a label, so a reader with a Windows machine can see WindowsFormsSynchronizationContext without a debugger. The worker takes an IProgress<int>, not the form and not the bar: it cannot touch the UI even by mistake, and it can be called from a console test with an inline implementation.

A context that runs

The same idea in a program that runs. QueueContext keeps a queue of delegates; Post adds and returns; Send adds and waits; the program drains the queue by hand, which stands in for the message loop. Built and run:

using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; Thread.CurrentThread.Name = "ui"; Console.WriteLine("a synchronization context of our own"); Console.WriteLine($"context: {SynchronizationContext.Current?.GetType().Name ?? "null"}"); var queue = new QueueContext(); SynchronizationContext.SetSynchronizationContext(queue); Console.WriteLine($"context: {SynchronizationContext.Current?.GetType().Name}"); IProgress<int> progress = new Progress<int>(value => Console.WriteLine($"progress {value} in {Thread.CurrentThread.Name}")); progress.Report(1); Console.WriteLine("main: after Report"); queue.RunPending(); var worker = new Thread(() => { queue.Send(_ => Console.WriteLine($"send runs in {Thread.CurrentThread.Name}"), null); Console.WriteLine("worker: Send returned"); }) { Name = "worker", }; worker.Start(); while (worker.IsAlive) { queue.RunOne(); } worker.Join(); Console.WriteLine("main: done"); internal sealed class QueueContext : SynchronizationContext { private readonly Queue<(SendOrPostCallback Callback, object? State)> _queue = new(); public override void Post(SendOrPostCallback d, object? state) { lock (_queue) { _queue.Enqueue((d, state)); } } public override void Send(SendOrPostCallback d, object? state) { if (Thread.CurrentThread.Name == "ui") { d(state); return; } using var done = new ManualResetEventSlim(); Post( _ => { try { d(state); } finally { done.Set(); } }, null); done.Wait(); } public void RunPending() { while (TryTake(out var item)) { item.Callback(item.State); } } public void RunOne() { if (TryTake(out var item)) { item.Callback(item.State); return; } Thread.Sleep(10); } private bool TryTake(out (SendOrPostCallback Callback, object? State) item) { lock (_queue) { if (_queue.Count == 0) { item = default; return false; } item = _queue.Dequeue(); return true; } } }

dotnet run

a synchronization context of our own
context: null
context: QueueContext
main: after Report
progress 1 in ui
send runs in ui
worker: Send returned
main: done

The output is the real run, and it shows the two kinds of call. progress.Report used Post: it returned before the callback ran, which is why the report line is after the main line. Send from the worker waited: its delegate ran in the thread named ui and the worker continued only when it was done. That is BeginInvoke and Invoke in their general form, and the same queue a WinForms message loop drains between messages.

The real Progress<T> posts the callback and does not wait, which is exactly the line order above. Its callback runs later, on the captured context. If the UI thread has stopped pumping messages by then, the callback never runs; if the form it posts through has been disposed, the post itself can throw. A background operation that may outlive its form should watch a cancellation token rather than post to controls that may be gone.

When to use which

Exercises

  1. Replace Progress<int> in the run with a Send and explain which lines change order.
  2. Add a second thread that posts at the same time as the worker sends, and explain why the queue order is the order of the calls, not of the threads.
  3. Write an InlineProgress<T> that runs its callback at once and use it where the form uses Progress<T>; say which code would break.

Questions

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

  1. What does SynchronizationContext.Current hold in a console program at startup?

    Answer

    null, because no context was installed

    The run printed null before the program set one.

  2. Which method waits for the delegate?

    Answer

    Send

    Post queues and returns; Send queues and waits.

  3. Which context does WinForms install on the UI thread?

    Answer

    WindowsFormsSynchronizationContext

    Its Post and Send are BeginInvoke and Invoke on a hidden control.

  4. What does Progress<T> capture?

    Answer

    The synchronization context of the thread that created it

    Report posts to that context, whatever thread calls it.

  5. Why is the progress line printed after "main: after Report"?

    Answer

    Report posts and returns; the callback runs when the queue is drained

    Post is asynchronous, and RunPending comes later.

  6. In which thread did the worker's Send delegate run?

    Answer

    The thread named ui

    The context runs it on the owner thread, and Send waits.

  7. What does await do with the current context?

    Answer

    It captures it and resumes on it after the await

    That is why the line after an await in a handler is on the UI thread.

  8. Why should a library use ConfigureAwait(false)?

    Answer

    So it does not depend on or resume on a UI context

    The application keeps its context; the library stays neutral.

  9. What happens to a Progress<T> report after its form has closed?

    Answer

    The callback never runs; it is dropped

    Post to a dead context is a drop, not a crash.

  10. Why is IProgress<T> better than a control in a worker's signature?

    Answer

    The worker cannot touch the UI and can run under a console test

    It is the seam that keeps the model headless.

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