BackgroundWorker and cancellation

Before async and await, WinForms had its own answer for work that must not block the window: BackgroundWorker. It is still in the framework and still in old code, and its three events are a clear model of what a background operation has to report. The modern answer is a Task with a CancellationToken, and the course teaches both, because a reader will meet both.

BackgroundWorker

A BackgroundWorker runs one method on a thread of its own and marshals its reports back to the thread that created it. It has three events and three properties:

Two details of its design are worth knowing because they differ from a Task. CancelAsync does not stop the thread: it sets CancellationPending, and the DoWork method has to look. And e.Cancel = true is what makes RunWorkerCompleted report Cancelled; returning without it looks like success. Reading e.Result when the worker was cancelled or failed throws InvalidOperationException, which is the documented behaviour and a common crash.

A form with a worker

A progress bar, a Start and a Cancel. The worker is a field created in the constructor, so the handlers are subscribed once. Built and not run:

using System; using System.ComponentModel; 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 ProgressBar _bar = new() { Location = new Point(16, 20), Size = new Size(320, 20), Maximum = 100 }; private readonly Label _status = new() { Location = new Point(16, 48), AutoSize = true }; private readonly Button _start = new() { Text = "&Start", Location = new Point(16, 80), Size = new Size(100, 27) }; private readonly Button _cancel = new() { Text = "&Cancel", Location = new Point(124, 80), Size = new Size(100, 27), Enabled = false }; private readonly BackgroundWorker _worker = new() { WorkerReportsProgress = true, WorkerSupportsCancellation = true, }; public Form1() { Text = "BackgroundWorker"; ClientSize = new Size(360, 130); _start.Click += (sender, e) => StartWork(); _cancel.Click += (sender, e) => _worker.CancelAsync(); _worker.DoWork += OnWork; _worker.ProgressChanged += OnProgress; _worker.RunWorkerCompleted += OnCompleted; Controls.Add(_bar); Controls.Add(_status); Controls.Add(_start); Controls.Add(_cancel); } private void StartWork() { if (_worker.IsBusy) { return; } _start.Enabled = false; _cancel.Enabled = true; _bar.Value = 0; _status.Text = "working"; _worker.RunWorkerAsync(); } private void OnWork(object? sender, DoWorkEventArgs e) { for (var i = 1; i <= 10; i++) { if (_worker.CancellationPending) { e.Cancel = true; return; } Thread.Sleep(200); _worker.ReportProgress(i * 10); } } private void OnProgress(object? sender, ProgressChangedEventArgs e) => _bar.Value = e.ProgressPercentage; private void OnCompleted(object? sender, RunWorkerCompletedEventArgs e) { _start.Enabled = true; _cancel.Enabled = false; if (e.Cancelled) { _status.Text = "cancelled"; } else if (e.Error is not null) { _status.Text = e.Error.Message; } else { _status.Text = "done"; } } }

dotnet build app.csproj

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

The listing is built and not run. The three handlers are on the form and the loop is in OnWork, but only OnProgress and OnCompleted may touch a control: they run on the UI thread, and OnWork runs on the worker's thread. The IsBusy guard makes a double click harmless even before the button is disabled.

Cancellation that runs

The modern cancellation is a CancellationToken: the worker is given a token, the caller holds the CancellationTokenSource that can cancel it, and every wait takes the token. The program below cancels itself from its own progress handler, and was built and run here:

using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; Console.WriteLine("a loop that can be cancelled"); var cts = new CancellationTokenSource(); var reporter = new InlineProgress(); reporter.Changed += value => { if (value == 3) { cts.Cancel(); } }; try { await CountAsync(10, reporter, cts.Token); Console.WriteLine("finished without cancellation"); } catch (OperationCanceledException error) { Console.WriteLine($"cancelled: {error.CancellationToken.IsCancellationRequested}"); } Console.WriteLine($"reported: {string.Join(", ", reporter.Values)}"); var second = new CancellationTokenSource(); var full = new InlineProgress(); var steps = await CountAsync(5, full, second.Token); Console.WriteLine($"completed {steps} steps: {string.Join(", ", full.Values)}"); static async Task<int> CountAsync(int count, InlineProgress progress, CancellationToken token) { for (var i = 1; i <= count; i++) { await Task.Delay(5, token); token.ThrowIfCancellationRequested(); progress.Report(i); } return count; } internal sealed class InlineProgress : IProgress<int> { public event Action<int>? Changed; public List<int> Values { get; } = new(); public void Report(int value) { Values.Add(value); Changed?.Invoke(value); } }

dotnet run

a loop that can be cancelled
cancelled: True
reported: 1, 2, 3
completed 5 steps: 1, 2, 3, 4, 5

The output is the real run. The third report cancelled the source, and the next Task.Delay observed the token and threw OperationCanceledException; the catch saw it and the values stopped at three. The second run had a token that was never cancelled and finished its five steps. ThrowIfCancellationRequested is the explicit check for a loop that does no waiting, where nothing else would notice the token.

The token is passed down, never stored in a static and never checked by reading the source: a worker that can cancel its own source can never be stopped from outside. The source belongs to the screen or the service that started the work, and the token is the read-only view it hands out.

The order of the events

A small class with the same three events and the same rule shows the order a worker produces, including a cancelled run. It was built and run here:

using System; Console.WriteLine("the events of a background worker, in order"); var item = new WorkItem(); item.Started += () => Console.WriteLine("DoWork started"); item.Progressed += value => Console.WriteLine($"progress {value}"); item.Completed += (cancelled, error) => Console.WriteLine($"completed: cancelled {cancelled}, error {error ?? "none"}"); item.Run(4, cancelAfter: 3); var second = new WorkItem(); second.Started += () => Console.WriteLine("second: started"); second.Progressed += value => Console.WriteLine($"second: progress {value}"); second.Completed += (cancelled, error) => Console.WriteLine($"second: completed, cancelled {cancelled}"); second.Run(4, cancelAfter: 10); internal sealed class WorkItem { public event Action? Started; public event Action<int>? Progressed; public event Action<bool, string?>? Completed; public void Run(int steps, int cancelAfter) { Started?.Invoke(); for (var i = 1; i <= steps; i++) { if (i > cancelAfter) { Completed?.Invoke(true, null); return; } Progressed?.Invoke(i); } Completed?.Invoke(false, null); } }

dotnet run

the events of a background worker, in order
DoWork started
progress 1
progress 2
progress 3
completed: cancelled True, error none
second: started
second: progress 1
second: progress 2
second: progress 3
second: progress 4
second: completed, cancelled False

The output is the real run. Started comes first, then every progress, then exactly one completion, cancelled or not; the cancelled run stops before its fourth step and reports it. That is the contract a form depends on: the completion handler undoes the disable, and a missing completion leaves the button grey forever.

Which one to use

The two share the same rule about controls: only the UI thread may touch them. BackgroundWorker enforces it by marshalling two of its three events; a Task enforces nothing, and the async handler gets back to the UI thread by capturing the context. Both fail the same way when the rule is broken.

Exercises

  1. Add an e.Result to DoWork and read it in the completion handler; explain what happens if the run was cancelled.
  2. Change the cancellation program to cancel after five reports and check the printed values.
  3. Rewrite the form's worker as an async void handler and list which of the three handlers disappear.

Questions

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

  1. On which thread does DoWork run?

    Answer

    A thread of the worker, not the UI thread

    That is why it must not touch a control.

  2. On which thread does ProgressChanged run?

    Answer

    The thread that created the worker

    The worker marshals it, which is its main convenience.

  3. What does CancelAsync do?

    Answer

    Sets CancellationPending, which DoWork has to look at

    The method must cooperate and set e.Cancel.

  4. What makes RunWorkerCompleted report Cancelled?

    Answer

    e.Cancel = true in DoWork before returning

    A return without the flag looks like success.

  5. Which property must be true before ReportProgress works?

    Answer

    WorkerReportsProgress

    Without it ReportProgress throws.

  6. What did the cancellation run report before it stopped?

    Answer

    1, 2, 3

    The fourth wait observed the token and threw.

  7. What does Task.Delay(5, token) do when the token is cancelled?

    Answer

    Throws OperationCanceledException

    The catch in the run saw the exception.

  8. Who should own the CancellationTokenSource?

    Answer

    The code that starts the work, handing out only the token

    A worker that owns its source cannot be stopped from outside.

  9. How many completion events does a finished worker raise?

    Answer

    Exactly one, cancelled or not

    The run shows one completion per run.

  10. Which pair is the modern replacement for BackgroundWorker?

    Answer

    A Task with await, IProgress and a CancellationToken

    It composes and propagates exceptions through the task.

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