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);
    else
      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.


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in .NET, Async, C#, WinForms. Bookmark the permalink. Follow any comments here with the RSS feed for this post.