Keep Windows Forms responsive with async work

Windows Forms controls belong to their creating thread. Start CPU-bound work through Task.Run, await it from a UI event, then update the controls after execution returns to the UI context.

Use asynchronous I/O APIs directly for I/O-bound work. Wrapping every asynchronous operation in a new thread is unnecessary.

Run a responsive form

On Windows, create dotnet new winforms -n AsyncDemo -f net10.0, replace Program.cs, then run the project.

C#
using System.Windows.Forms;

internal static class Program {
	[STAThread]
	private static void Main() {
		Application.EnableVisualStyles();
		var form = new Form { Text = "Async work" };
		var button = new Button { Text = "Calculate", Dock = DockStyle.Top };
		var label = new Label { Dock = DockStyle.Bottom };
		form.Controls.AddRange([button, label]);
		button.Click += async (_, _) => {
			button.Enabled = false;
			try {
				var sum = await Task.Run(() => Enumerable.Range(1, 1_000_000).Sum(x => (long)x));
				if (!form.IsDisposed) label.Text = sum.ToString();
			} catch (Exception ex) { if (!form.IsDisposed) label.Text = ex.Message; } finally { if (!button.IsDisposed) button.Enabled = true; }
		};
		Application.Run(form);
	}
}

Click Calculate. The label shows 500000500000, and the button becomes available again.

Marshal independent callbacks

The continuation above returns to the captured UI context because it began in the Click event. A callback already running on a worker thread has no such guarantee. On .NET 9 and later, await control.InvokeAsync(() => control.Text = "Ready") marshals the update without blocking that worker. Older .NET Framework code can use BeginInvoke with appropriate lifetime checks.

Avoid .Wait() and .Result on the UI thread. Add cancellation for substantial work and bind it to the form's lifetime. The tiny computation here does not demonstrate a cancellable operation.

Official references

How to handle cross-thread operations with controls - Windows Forms
Learn how to implement multithreading in your app by calling cross-thread controls in a thread-safe way. If you encounter the 'cross-thread operation not valid' error, use the InvokeRequired property to detect this error. The BackgroundWorker component is also an alternative to creating new threads.
https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-make-thread-safe-calls
Thread-safe calls to controls

Author: Herman Schoenfeld