ProgressBar and Timer

A ProgressBar shows how far a job has come, and a Timer is the control that makes a WinForms application do something later without a worker thread. The two appear together in every long job that reports itself, which is why they share a lesson: the timer ticks, the handler computes a percentage and moves the bar.

ProgressBar

using System; using System.Drawing; 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, 16), Size = new Size(300, 20), Minimum = 0, Maximum = 100, Step = 10, Style = ProgressBarStyle.Continuous, }; private readonly Label _status = new() { Location = new Point(16, 48), AutoSize = true }; public Form1() { Text = "Progress"; ClientSize = new Size(340, 90); for (var step = 0; step < 10; step++) { _bar.PerformStep(); } _status.Text = $"{_bar.Value} of {_bar.Maximum}"; Controls.Add(_bar); Controls.Add(_status); } }

dotnet build app.csproj

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

The listing is built and not run. The constructor advances the bar ten times with PerformStep(), which adds Step each time and clamps at Maximum. A job that reports itself calls Increment(n) or assigns Value from a percentage, and both clamp: a value above the maximum becomes the maximum, a value below the minimum becomes the minimum. There is no exception and no way to notice the clamp from the control, which is why the arithmetic in the last section is worth writing once.

Styles and steps

A progress bar has one rule that no property expresses: the value must reach the maximum when the job ends, including the path where it fails. A form that leaves the bar at 90 per cent after an error tells the user that something is still running.

Timer

using System; using System.Drawing; 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 System.Windows.Forms.Timer _timer = new() { Interval = 500 }; private readonly Label _clock = new() { Location = new Point(16, 16), AutoSize = true }; private int _ticks; public Form1() { Text = "A timer"; ClientSize = new Size(320, 80); _timer.Tick += OnTick; _timer.Start(); Controls.Add(_clock); } private void OnTick(object? sender, EventArgs e) { _ticks++; _clock.Text = $"tick {_ticks} at {DateTime.Now:HH:mm:ss}"; if (_ticks == 10) { _timer.Stop(); } } }

dotnet build app.csproj

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

The listing is built and not run. Interval is milliseconds, Start and Stop are the same as Enabled = true and false, and Tick runs on the user-interface thread, inside the message loop. That is the useful property and the trap: the handler can touch controls without Invoke, and a handler that takes longer than the interval delays everything else in the window, including the next tick.

Three different classes in .NET are called Timer, and a WinForms program uses the one in System.Windows.Forms:

A Timer is a component, not a control: it has no Location and is not drawn. Dropping one on a form in the designer puts it in the component tray below the form, and the designer writes a field for it in Form1.Designer.cs like any other control.

A progress model that runs

The arithmetic a progress bar needs is a range, a value, a percentage and a question. None of that needs a control, and it runs here:

using System; var bar = new Progress(0, 10); foreach (var step in new[] { 1, 4, 10, 12 }) { bar.Set(step); var filled = bar.Percent / 10; Console.WriteLine($"step {step,2}: {bar.Percent,3}% [{new string('#', filled)}{new string('.', 10 - filled)}] done={bar.IsDone}"); } Console.WriteLine($"clamped: {bar.Value} of {bar.Maximum}"); internal sealed class Progress { public Progress(int minimum, int maximum) { Minimum = minimum; Maximum = maximum; } public int Minimum { get; } public int Maximum { get; } public int Value { get; private set; } public int Percent => Maximum == Minimum ? 0 : (Value - Minimum) * 100 / (Maximum - Minimum); public bool IsDone => Value >= Maximum; public void Set(int value) => Value = Math.Clamp(value, Minimum, Maximum); }

dotnet run

step  1:  10% [#.........] done=False
step  4:  40% [####......] done=False
step 10: 100% [##########] done=True
step 12: 100% [##########] done=True
clamped: 10 of 10

The output is the real run. The last step of twelve shows the clamp, which is the same clamp the control applies. The percentage divides by the width of the range, not by the maximum, so a bar from 100 to 200 works the same as one from 0 to 100; the guard for an empty range is the one division a reader should not forget. In a form this model is a field, the timer's Tick calls Set with the number of finished items, and the handler assigns _bar.Value = progress.Percent.

Exercises

  1. Add a second constructor to Progress that takes no arguments and starts at 0 of 100, and run the program.
  2. Make Percent round to the nearest integer instead of truncating, and run it again.
  3. Explain from the documentation why a System.Windows.Forms.Timer handler may touch a control while a System.Timers.Timer handler may not.

Questions

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

  1. What unit is Timer.Interval in?

    Answer

    Milliseconds

    Five hundred is half a second, which is what the listing sets.

  2. On which thread does a System.Windows.Forms.Timer raise Tick?

    Answer

    The user-interface thread, inside the message loop

    That is why the handler can touch controls without Invoke, and why a slow handler delays the window.

  3. What does PerformStep() do?

    Answer

    Adds Step to Value and clamps at Maximum

    Increment(n) is the same with another amount.

  4. Which style ignores Value and animates?

    Answer

    Marquee

    Marquee is for a job whose length is unknown.

  5. What happens to a Value above Maximum?

    Answer

    It is clamped to Maximum

    The control clamps silently, which is why the model clamps too.

  6. Which Timer class does a WinForms form use?

    Answer

    System.Windows.Forms.Timer

    Its Tick event runs on the UI thread, which the other two do not.

  7. What is wrong with touching a control from a System.Timers.Timer callback?

    Answer

    The callback runs on a thread-pool thread, not the UI thread

    Controls belong to the UI thread; the call has to be marshalled.

  8. What did the run print for step 12?

    Answer

    100% and done=True

    The value was clamped to the maximum of 10 first.

  9. Why does Percent divide by the width of the range rather than by Maximum?

    Answer

    So a range from 100 to 200 reports 0 to 100 per cent like any other

    The percentage is a position inside the range, not inside the maximum.

  10. What does a form owe the user when a job fails halfway?

    Answer

    It reaches the maximum or hides the bar, so the bar never looks unfinished

    A bar at 90 per cent after an error says that something is still running.

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