Asynchronous Control Updates In C#/.NET/WinForms

Every .NET WinForms project I’ve written, since .NET 2.0, has included some form of this code:

public static class ControlExtensions
  public static void Do<TControl>(this TControl control, Action<TControl> action)
    where TControl: Control
    if (control.InvokeRequired)
      control.Invoke(action, control);

It’s a simple extension method that allows any UI control to update itself when called from an asynchronous method – whether it’s running from a .BeginInvoke() call, a BackgroundWorker, a ThreadPool thread, or any other form of asynchronous call. It’s simple and effective in managing UI updates from asynchronous methods.

I’m currently using it to update a progress bar, like this:

private void SetProgress(int percentage)
updateProgressBar.Do(ctl =>
ctl.Value = percentage;

The best part is that it’s aware of the control type through the use of generics. You don’t have to cast from a generic Control type so that you can access the specific methods and properties of your specific control type.

I’m sure this code has been written and blogged about thousands of times (I may have even blogged it in the past… I don’t remember, honestly). I just wrote this code again, though, so I wanted to capture it someplace useful.

Responding To Growl Notification Clicks With MacRuby