Async handlers and the freeze

An event handler returns void, so it cannot return a Task, so a handler that waits for work is an async void method. That one keyword explains most of the rules of this lesson: the message loop cannot await the handler, the handler cannot report its failure by a return value, and the exception goes somewhere else.

async void is the handler

An async Task method is a value the caller can await and whose exception the caller can catch. An async void method has neither: the caller gets nothing, and an exception it throws is rethrown on the captured context, where the message loop catches it and raises Application.ThreadException. If nothing handles that event, the application shows its unhandled-exception dialog.

That is why the rule is not "never use async void" but "use it only where a void delegate is required": an event handler, and the entry point of a form. Every other async method returns a Task and is awaited.

Inside the handler, await captures the current SynchronizationContext, which on the UI thread is the WinForms one. The line after the await therefore runs on the UI thread, and the controls can be touched without Invoke. Before the await, the handler runs synchronously, which is why disabling the button at the top is not a race.

A handler that awaits

The shape every async handler should have: disable what must not be pressed twice, say what is happening, try the work, report the failure, and put the re-enable in a finally. Built and not run:

using System; using System.Drawing; using System.IO; 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 TextBox _path = new() { Location = new Point(16, 16), Width = 300 }; private readonly TextBox _content = new() { Location = new Point(16, 48), Size = new Size(340, 120), Multiline = true }; private readonly Label _status = new() { Location = new Point(16, 176), AutoSize = true }; private readonly Button _open = new() { Text = "&Open", Location = new Point(324, 14), Size = new Size(80, 27) }; public Form1() { Text = "Async handler"; ClientSize = new Size(380, 210); _open.Click += OnOpen; Controls.Add(_path); Controls.Add(_content); Controls.Add(_status); Controls.Add(_open); } private async void OnOpen(object? sender, EventArgs e) { _open.Enabled = false; _status.Text = "Loading..."; try { _content.Text = await File.ReadAllTextAsync(_path.Text); _status.Text = "Loaded."; } catch (IOException error) { _status.Text = error.Message; } catch (UnauthorizedAccessException error) { _status.Text = error.Message; } finally { _open.Enabled = true; } } }

dotnet build app.csproj

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

The listing is built and not run. File.ReadAllTextAsync does its reading on the thread pool and returns a Task<string>; the await gives back the string on the UI thread. The two catches are separate because the handling differs: a missing file is a message, a denied file is a message with a permission hint in a real form. The finally runs whether the read succeeded, failed or was cancelled, so the button cannot stay grey forever.

async void handlers are the one place where a catch-all is worth it, because the alternative is the unhandled-exception dialog. A catch (Exception) that logs and shows a status line is the last line of defence in a handler, not a substitute for the specific catches above it.

The freeze and the deadlock

The freeze is any long call on the UI thread, whether it is synchronous code or a blocking wait. Thread.Sleep(5000) in a handler freezes the window for five seconds: no repaint, no click, the title bar says "Not responding". The same five seconds inside await Task.Delay(5000) leave the window alive, because the thread returns to the message loop.

The worse version blocks on an async call. This program compiles, and it is built here only, because on Windows it would deadlock:

using System; using System.Drawing; using System.IO; 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 TextBox _path = new() { Location = new Point(16, 16), Width = 300, Text = "notes.txt" }; private readonly TextBox _content = new() { Location = new Point(16, 48), Size = new Size(340, 120), Multiline = true }; public Form1() { Text = "Never write this"; ClientSize = new Size(380, 180); Load += OnLoad; Controls.Add(_path); Controls.Add(_content); } private void OnLoad(object? sender, EventArgs e) { // The UI thread blocks here, and the continuation of ReadAllTextAsync // wants the UI thread: neither can move. _content.Text = File.ReadAllTextAsync(_path.Text).Result; } }

dotnet build app.csproj

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

The listing is built and not run. Result blocks the UI thread until the task completes. The task's continuation was scheduled on the UI thread, by the context captured when the read began, so it waits for the thread that is waiting for it. The window freezes, the operation never finishes, and no exception explains it. GetAwaiter().GetResult() has the same shape; the only fix is not to block, which means making the caller async all the way up.

The same rule covers Task.Wait, Task.WaitAll and a lock held across an await. A lock cannot even be held across an await in C#: the compiler rejects it, because the continuation may run on another thread and a lock is thread-affine.

Await against Wait

The difference between the two is visible in a console program, where there is no context to deadlock. It was built and run here:

using System; using System.Threading.Tasks; Console.WriteLine("await against Wait"); var failing = Task.Run(() => throw new InvalidOperationException("boom")); try { await failing; } catch (Exception error) { Console.WriteLine($"await: {error.GetType().Name}: {error.Message}"); } var again = Task.Run(() => throw new InvalidOperationException("boom")); try { again.Wait(); } catch (Exception error) { Console.WriteLine($"Wait: {error.GetType().Name}: {error.Message}"); } Console.WriteLine($"faulted: {again.IsFaulted}, inner: {again.Exception?.InnerException?.GetType().Name}"); var sum = await AddAsync(2, 3); Console.WriteLine($"sum: {sum}"); var all = await Task.WhenAll(AddAsync(1, 1), AddAsync(2, 2), AddAsync(3, 3)); Console.WriteLine($"all: {string.Join(", ", all)}"); static async Task<int> AddAsync(int a, int b) { await Task.Delay(5); return a + b; }

dotnet run

await against Wait
await: InvalidOperationException: boom
Wait: AggregateException: One or more errors occurred. (boom)
faulted: True, inner: InvalidOperationException
sum: 5
all: 2, 4, 6

The output is the real run. await unwraps the exception and rethrows the original InvalidOperationException; Wait throws the AggregateException that wraps it. Both are the same failure, and a handler that catches the specific type needs the first form. The Exception property of a faulted task keeps the aggregate, which is where the inner exception is; await uses exactly that property to unwrap.

Task.WhenAll returned the results in the order of the tasks, not in the order they finished, which is the guarantee that makes it usable for a set of parallel reads. If any of them fails, the await throws the first exception and the others are in the aggregate.

Rules for handlers

Exercises

  1. Add a second button that reads three files with Task.WhenAll and puts the combined text in the box.
  2. Make the deadlock listing into a working one by awaiting the read, and say which lines changed.
  3. Subscribe to Application.ThreadException in Main and explain when the handler runs.

Questions

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

  1. Why is an event handler async void?

    Answer

    The event delegate returns void, so the handler cannot return a Task

    The delegate signature fixes the return type.

  2. Where does the line after an await in a handler run?

    Answer

    On the UI thread, because the context was captured

    That is why no Invoke is needed after the await.

  3. Where does an exception from an async void handler go?

    Answer

    To the captured context, where the message loop raises ThreadException

    The handler has no Task to carry it.

  4. What does await do with a faulted task that Wait does not?

    Answer

    It rethrows the original exception instead of the AggregateException

    The run printed InvalidOperationException for await and AggregateException for Wait.

  5. What does the deadlock listing block on?

    Answer

    Task.Result on the UI thread, while the continuation needs the UI thread

    Neither the thread nor the task can move.

  6. Where does the re-enable of the button belong?

    Answer

    In a finally, so it runs on every path

    A failed read must not leave the button grey.

  7. Why is Thread.Sleep worse than await Task.Delay in a handler?

    Answer

    Sleep blocks the UI thread and the window stops responding

    A blocked message loop cannot repaint or dispatch clicks.

  8. In which order does Task.WhenAll return its results?

    Answer

    The order of the tasks, not the order they finished

    The run printed 2, 4, 6 for tasks started in that order.

  9. Why can a lock not be held across an await?

    Answer

    The continuation may run on another thread, and a lock is thread-affine

    The compiler rejects it for that reason.

  10. What does a handler pass to long-running work?

    Answer

    An IProgress of T and a CancellationToken

    The work stays free of the UI and can be cancelled.

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